1 /* Copyright (C) 1989, 1997 Aladdin Enterprises. All rights reserved. */
3 /*$Id: ansi2knr.c,v 1.1.1.1 2003/03/05 07:25:51 mtr Exp $*/
4 /* Convert ANSI C function definitions to K&R ("traditional C") syntax */
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.
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 or, if there is no file named COPYLEFT, a file named COPYING. Among other
18 things, the copyright notice and this notice must be preserved on all
21 We explicitly state here what we believe is already implied by the GPL: if
22 the ansi2knr program is distributed as a separate set of sources and a
23 separate executable file which are aggregated on a storage medium together
24 with another program, this in itself does not bring the other program under
25 the GPL, nor does the mere fact that such a program or the procedures for
26 constructing it invoke the ansi2knr executable bring any other part of the
27 program under the GPL.
32 ansi2knr [--filename FILENAME] [INPUT_FILE [OUTPUT_FILE]]
33 * --filename provides the file name for the #line directive in the output,
34 * overriding input_file (if present).
35 * If no input_file is supplied, input is read from stdin.
36 * If no output_file is supplied, output goes to stdout.
37 * There are no error messages.
39 * ansi2knr recognizes function definitions by seeing a non-keyword
40 * identifier at the left margin, followed by a left parenthesis,
41 * with a right parenthesis as the last character on the line,
42 * and with a left brace as the first token on the following line
43 * (ignoring possible intervening comments).
44 * It will recognize a multi-line header provided that no intervening
45 * line ends with a left or right brace or a semicolon.
46 * These algorithms ignore whitespace and comments, except that
47 * the function name must be the first thing on the line.
48 * The following constructs will confuse it:
49 * - Any other construct that starts at the left margin and
50 * follows the above syntax (such as a macro or function call).
51 * - Some macros that tinker with the syntax of the function header.
55 * The original and principal author of ansi2knr is L. Peter Deutsch
56 * <ghost@aladdin.com>. Other authors are noted in the change history
57 * that follows (in reverse chronological order):
58 lpd 97-12-08 made input_file optional; only closes input and/or
59 output file if not stdin or stdout respectively; prints
60 usage message on stderr rather than stdout; adds
61 --filename switch (changes suggested by
62 <ceder@lysator.liu.se>)
63 lpd 96-01-21 added code to cope with not HAVE_CONFIG_H and with
64 compilers that don't understand void, as suggested by
66 lpd 96-01-15 changed to require that the first non-comment token
67 on the line following a function header be a left brace,
68 to reduce sensitivity to macros, as suggested by Tom Lane
70 lpd 95-06-22 removed #ifndefs whose sole purpose was to define
71 undefined preprocessor symbols as 0; changed all #ifdefs
72 for configuration symbols to #ifs
73 lpd 95-04-05 changed copyright notice to make it clear that
74 including ansi2knr in a program does not bring the entire
76 lpd 94-12-18 added conditionals for systems where ctype macros
77 don't handle 8-bit characters properly, suggested by
78 Francois Pinard <pinard@iro.umontreal.ca>;
79 removed --varargs switch (this is now the default)
80 lpd 94-10-10 removed CONFIG_BROKETS conditional
81 lpd 94-07-16 added some conditionals to help GNU `configure',
82 suggested by Francois Pinard <pinard@iro.umontreal.ca>;
83 properly erase prototype args in function parameters,
84 contributed by Jim Avera <jima@netcom.com>;
85 correct error in writeblanks (it shouldn't erase EOLs)
86 lpd 89-xx-xx original version
89 /* Most of the conditionals here are to make ansi2knr work with */
90 /* or without the GNU configure machinery. */
102 For properly autoconfiguring ansi2knr, use AC_CONFIG_HEADER(config.h).
103 This will define HAVE_CONFIG_H and so, activate the following lines.
106 # if STDC_HEADERS || HAVE_STRING_H
109 # include <strings.h>
112 #else /* not HAVE_CONFIG_H */
114 /* Otherwise do it the hard way */
117 # include <strings.h>
120 extern int strlen(), strncmp();
126 #endif /* not HAVE_CONFIG_H */
132 malloc and free should be declared in stdlib.h,
133 but if you've got a K&R compiler, they probably aren't.
139 extern char *malloc();
142 extern char *malloc();
150 * The ctype macros don't always handle 8-bit characters correctly.
151 * Compensate for this here.
154 # undef HAVE_ISASCII /* just in case */
155 # define HAVE_ISASCII 1
158 #if STDC_HEADERS || !HAVE_ISASCII
159 # define is_ascii(c) 1
161 # define is_ascii(c) isascii(c)
164 #define is_space(c) (is_ascii(c) && isspace(c))
165 #define is_alpha(c) (is_ascii(c) && isalpha(c))
166 #define is_alnum(c) (is_ascii(c) && isalnum(c))
168 /* Scanning macros */
169 #define isidchar(ch) (is_alnum(ch) || (ch) == '_')
170 #define isidfirstchar(ch) (is_alpha(ch) || (ch) == '_')
172 /* Forward references */
178 /* The main program */
186 #define bufsize 5000 /* arbitrary size */
191 "Usage: ansi2knr [--filename FILENAME] [INPUT_FILE [OUTPUT_FILE]]\n";
193 * In previous versions, ansi2knr recognized a --varargs switch.
194 * If this switch was supplied, ansi2knr would attempt to convert
195 * a ... argument to va_alist and va_dcl; if this switch was not
196 * supplied, ansi2knr would simply drop any such arguments.
197 * Now, ansi2knr always does this conversion, and we only
198 * check for this switch for backward compatibility.
200 int convert_varargs = 1;
202 while ( argc > 1 && argv[1][0] == '-' ) {
203 if ( !strcmp(argv[1], "--varargs") ) {
209 if ( !strcmp(argv[1], "--filename") && argc > 2 ) {
215 fprintf(stderr, "Unrecognized switch: %s\n", argv[1]);
216 fprintf(stderr, usage);
222 fprintf(stderr, usage);
225 out = fopen(argv[2], "w");
227 fprintf(stderr, "Cannot open output file %s\n", argv[2]);
232 in = fopen(argv[1], "r");
234 fprintf(stderr, "Cannot open input file %s\n", argv[1]);
244 fprintf(out, "#line 1 \"%s\"\n", filename);
245 buf = malloc(bufsize);
247 while ( fgets(line, (unsigned)(buf + bufsize - line), in) != NULL )
249 test: line += strlen(line);
250 switch ( test1(buf) )
252 case 2: /* a function header */
253 convert1(buf, out, 1, convert_varargs);
255 case 1: /* a function */
256 /* Check for a { at the start of the next line. */
258 f: if ( line >= buf + (bufsize - 1) ) /* overflow check */
260 if ( fgets(line, (unsigned)(buf + bufsize - line), in) == NULL )
262 switch ( *skipspace(more, 1) )
265 /* Definitely a function header. */
266 convert1(buf, out, 0, convert_varargs);
270 /* The next line was blank or a comment: */
271 /* keep scanning for a non-comment. */
272 line += strlen(line);
275 /* buf isn't a function header, but */
283 case -1: /* maybe the start of a function */
284 if ( line != buf + (bufsize - 1) ) /* overflow check */
287 default: /* not a function */
303 /* Skip over space and comments, in either direction. */
307 register int dir; /* 1 for forward, -1 for backward */
309 { while ( is_space(*p) )
311 if ( !(*p == '/' && p[dir] == '*') )
314 while ( !(*p == '*' && p[dir] == '/') )
316 return p; /* multi-line comment?? */
325 * Write blanks over part of a string.
326 * Don't overwrite end-of-line characters.
329 writeblanks(start, end)
333 for ( p = start; p < end; p++ )
334 if ( *p != '\r' && *p != '\n' )
340 * Test whether the string in buf is a function definition.
341 * The string may contain and/or end with a newline.
343 * 0 - definitely not a function definition;
344 * 1 - definitely a function definition;
345 * 2 - definitely a function prototype (NOT USED);
346 * -1 - may be the beginning of a function definition,
347 * append another line and look again.
348 * The reason we don't attempt to convert function prototypes is that
349 * Ghostscript's declaration-generating macros look too much like
350 * prototypes, and confuse the algorithms.
355 { register char *p = buf;
360 if ( !isidfirstchar(*p) )
361 return 0; /* no name at left margin */
362 bend = skipspace(buf + strlen(buf) - 1, -1);
365 case ';': contin = 0 /*2*/; break;
366 case ')': contin = 1; break;
367 case '{': return 0; /* not a function */
368 case '}': return 0; /* not a function */
369 default: contin = -1;
371 while ( isidchar(*p) )
376 return 0; /* not a function */
379 return 0; /* no parameters */
380 /* Check that the apparent function name isn't a keyword. */
381 /* We only need to check for keywords that could be followed */
382 /* by a left parenthesis (which, unfortunately, is most of them). */
383 { static char *words[] =
384 { "asm", "auto", "case", "char", "const", "double",
385 "extern", "float", "for", "if", "int", "long",
386 "register", "return", "short", "signed", "sizeof",
387 "static", "switch", "typedef", "unsigned",
388 "void", "volatile", "while", 0
392 int len = endfn - buf;
394 while ( (kp = *key) != 0 )
395 { if ( strlen(kp) == len && !strncmp(kp, buf, len) )
396 return 0; /* name is a keyword */
403 /* Convert a recognized function definition or header to K&R syntax. */
405 convert1(buf, out, header, convert_varargs)
408 int header; /* Boolean */
409 int convert_varargs; /* Boolean */
413 * The breaks table contains pointers to the beginning and end
417 unsigned num_breaks = 2; /* for testing */
423 /* Pre-ANSI implementations don't agree on whether strchr */
424 /* is called strchr or index, so we open-code it here. */
425 for ( endfn = buf; *(endfn++) != '('; )
428 breaks = (char **)malloc(sizeof(char *) * num_breaks * 2);
430 { /* Couldn't allocate break table, give up */
431 fprintf(stderr, "Unable to allocate break table!\n");
435 btop = breaks + num_breaks * 2 - 2;
437 /* Parse the argument list */
445 { /* Filled up break table. */
446 /* Allocate a bigger one and start over. */
447 free((char *)breaks);
452 /* Find the end of the argument */
453 for ( ; end == NULL; p++ )
457 if ( !level ) end = p;
460 if ( !level ) lp = p;
464 if ( --level < 0 ) end = p;
468 p = skipspace(p, 1) - 1;
474 /* Erase any embedded prototype parameters. */
476 writeblanks(lp + 1, rp);
477 p--; /* back up over terminator */
478 /* Find the name being declared. */
479 /* This is complicated because of procedure and */
480 /* array modifiers. */
482 { p = skipspace(p - 1, -1);
485 case ']': /* skip array dimension(s) */
486 case ')': /* skip procedure args OR name */
491 case ']': case ')': level++; break;
492 case '[': case '(': level--; break;
493 case '/': p = skipspace(p, -1) + 1; break;
497 if ( *p == '(' && *skipspace(p + 1, 1) == '*' )
498 { /* We found the name being declared */
499 while ( !isidfirstchar(*p) )
500 p = skipspace(p, 1) + 1;
508 found: if ( *p == '.' && p[-1] == '.' && p[-2] == '.' )
509 { if ( convert_varargs )
510 { *bp++ = "va_alist";
515 if ( bp == breaks + 1 ) /* sole argument */
516 writeblanks(breaks[0], p);
518 writeblanks(bp[-1] - 1, p);
523 { while ( isidchar(*p) ) p--;
528 while ( *p++ == ',' );
530 /* Make a special check for 'void' arglist */
531 if ( bp == breaks+2 )
532 { p = skipspace(breaks[0], 1);
533 if ( !strncmp(p, "void", 4) )
534 { p = skipspace(p+4, 1);
535 if ( p == breaks[2] - 1 )
536 { bp = breaks; /* yup, pretend arglist is empty */
537 writeblanks(breaks[0], p + 1);
541 /* Put out the function name and left parenthesis. */
543 while ( p != endfn ) putc(*p, out), p++;
544 /* Put out the declaration. */
547 for ( p = breaks[0]; *p; p++ )
548 if ( *p == '\r' || *p == '\n' )
552 { for ( ap = breaks+1; ap < bp; ap += 2 )
554 while ( isidchar(*p) )
560 /* Put out the argument declarations */
561 for ( ap = breaks+2; ap <= bp; ap += 2 )
565 fputs(breaks[0], out); /* any prior args */
566 fputs("va_dcl", out); /* the final arg */
570 fputs(breaks[0], out);
572 free((char *)breaks);