GAP 4.8.9 installation with standard packages -- copy to your CoCalc project to get it
/* Copyright (C) 1989, 2000 Aladdin Enterprises. All rights reserved. */12/*$Id: ansi2knr.c,v 1.1.1.1 2006/03/14 15:57:54 tege Exp $*/3/* Convert ANSI C function definitions to K&R ("traditional C") syntax */45/*6ansi2knr is distributed in the hope that it will be useful, but WITHOUT ANY7WARRANTY. No author or distributor accepts responsibility to anyone for the8consequences of using it or for whether it serves any particular purpose or9works at all, unless he says so in writing. Refer to the GNU General Public10License (the "GPL") for full details.1112Everyone is granted permission to copy, modify and redistribute ansi2knr,13but only under the conditions described in the GPL. A copy of this license14is supposed to have been given to you along with ansi2knr so you can know15your rights and responsibilities. It should be in a file named COPYLEFT,16or, if there is no file named COPYLEFT, a file named COPYING. Among other17things, the copyright notice and this notice must be preserved on all18copies.1920We explicitly state here what we believe is already implied by the GPL: if21the ansi2knr program is distributed as a separate set of sources and a22separate executable file which are aggregated on a storage medium together23with another program, this in itself does not bring the other program under24the GPL, nor does the mere fact that such a program or the procedures for25constructing it invoke the ansi2knr executable bring any other part of the26program under the GPL.27*/2829/*30* Usage:31ansi2knr [--filename FILENAME] [INPUT_FILE [OUTPUT_FILE]]32* --filename provides the file name for the #line directive in the output,33* overriding input_file (if present).34* If no input_file is supplied, input is read from stdin.35* If no output_file is supplied, output goes to stdout.36* There are no error messages.37*38* ansi2knr recognizes function definitions by seeing a non-keyword39* identifier at the left margin, followed by a left parenthesis, with a40* right parenthesis as the last character on the line, and with a left41* brace as the first token on the following line (ignoring possible42* intervening comments and/or preprocessor directives), except that a line43* consisting of only44* identifier1(identifier2)45* will not be considered a function definition unless identifier2 is46* the word "void", and a line consisting of47* identifier1(identifier2, <<arbitrary>>)48* will not be considered a function definition.49* ansi2knr will recognize a multi-line header provided that no intervening50* line ends with a left or right brace or a semicolon. These algorithms51* ignore whitespace, comments, and preprocessor directives, except that52* the function name must be the first thing on the line. The following53* constructs will confuse it:54* - Any other construct that starts at the left margin and55* follows the above syntax (such as a macro or function call).56* - Some macros that tinker with the syntax of function headers.57*/5859/*60* The original and principal author of ansi2knr is L. Peter Deutsch61* <[email protected]>. Other authors are noted in the change history62* that follows (in reverse chronological order):6364lpd 2000-04-12 backs out Eggert's changes because of bugs:65- concatlits didn't declare the type of its bufend argument;66- concatlits didn't recognize when it was inside a comment;67- scanstring could scan backward past the beginning of the string; when68- the check for \ + newline in scanstring was unnecessary.69702000-03-05 Paul Eggert <[email protected]>7172Add support for concatenated string literals.73* ansi2knr.c (concatlits): New decl.74(main): Invoke concatlits to concatenate string literals.75(scanstring): Handle backslash-newline correctly. Work with76character constants. Fix bug when scanning backwards through77backslash-quote. Check for unterminated strings.78(convert1): Parse character constants, too.79(appendline, concatlits): New functions.80* ansi2knr.1: Document this.8182lpd 1999-08-17 added code to allow preprocessor directives83wherever comments are allowed84lpd 1999-04-12 added minor fixes from Pavel Roskin85<[email protected]> for clean compilation with86gcc -W -Wall87lpd 1999-03-22 added hack to recognize lines consisting of88identifier1(identifier2, xxx) as *not* being procedures89lpd 1999-02-03 made indentation of preprocessor commands consistent90lpd 1999-01-28 fixed two bugs: a '/' in an argument list caused an91endless loop; quoted strings within an argument list92confused the parser93lpd 1999-01-24 added a check for write errors on the output,94suggested by Jim Meyering <[email protected]>95lpd 1998-11-09 added further hack to recognize identifier(void)96as being a procedure97lpd 1998-10-23 added hack to recognize lines consisting of98identifier1(identifier2) as *not* being procedures99lpd 1997-12-08 made input_file optional; only closes input and/or100output file if not stdin or stdout respectively; prints101usage message on stderr rather than stdout; adds102--filename switch (changes suggested by103<[email protected]>)104lpd 1996-01-21 added code to cope with not HAVE_CONFIG_H and with105compilers that don't understand void, as suggested by106Tom Lane107lpd 1996-01-15 changed to require that the first non-comment token108on the line following a function header be a left brace,109to reduce sensitivity to macros, as suggested by Tom Lane110<[email protected]>111lpd 1995-06-22 removed #ifndefs whose sole purpose was to define112undefined preprocessor symbols as 0; changed all #ifdefs113for configuration symbols to #ifs114lpd 1995-04-05 changed copyright notice to make it clear that115including ansi2knr in a program does not bring the entire116program under the GPL117lpd 1994-12-18 added conditionals for systems where ctype macros118don't handle 8-bit characters properly, suggested by119Francois Pinard <[email protected]>;120removed --varargs switch (this is now the default)121lpd 1994-10-10 removed CONFIG_BROKETS conditional122lpd 1994-07-16 added some conditionals to help GNU `configure',123suggested by Francois Pinard <[email protected]>;124properly erase prototype args in function parameters,125contributed by Jim Avera <[email protected]>;126correct error in writeblanks (it shouldn't erase EOLs)127lpd 1989-xx-xx original version128*/129130/* Most of the conditionals here are to make ansi2knr work with */131/* or without the GNU configure machinery. */132133#if HAVE_CONFIG_H134# include <config.h>135#endif136137#include <stdio.h>138#include <ctype.h>139140#if HAVE_CONFIG_H141142/*143For properly autoconfiguring ansi2knr, use AC_CONFIG_HEADER(config.h).144This will define HAVE_CONFIG_H and so, activate the following lines.145*/146147# if STDC_HEADERS || HAVE_STRING_H148# include <string.h>149# else150# include <strings.h>151# endif152153#else /* not HAVE_CONFIG_H */154155/* Otherwise do it the hard way */156157# ifdef BSD158# include <strings.h>159# else160# ifdef VMS161extern int strlen(), strncmp();162# else163# include <string.h>164# endif165# endif166167#endif /* not HAVE_CONFIG_H */168169#if STDC_HEADERS170# include <stdlib.h>171#else172/*173malloc and free should be declared in stdlib.h,174but if you've got a K&R compiler, they probably aren't.175*/176# ifdef MSDOS177# include <malloc.h>178# else179# ifdef VMS180extern char *malloc();181extern void free();182# else183extern char *malloc();184extern int free();185# endif186# endif187188#endif189190/* Define NULL (for *very* old compilers). */191#ifndef NULL192# define NULL (0)193#endif194195/*196* The ctype macros don't always handle 8-bit characters correctly.197* Compensate for this here.198*/199#ifdef isascii200# undef HAVE_ISASCII /* just in case */201# define HAVE_ISASCII 1202#else203#endif204#if STDC_HEADERS || !HAVE_ISASCII205# define is_ascii(c) 1206#else207# define is_ascii(c) isascii(c)208#endif209210#define is_space(c) (is_ascii(c) && isspace(c))211#define is_alpha(c) (is_ascii(c) && isalpha(c))212#define is_alnum(c) (is_ascii(c) && isalnum(c))213214/* Scanning macros */215#define isidchar(ch) (is_alnum(ch) || (ch) == '_')216#define isidfirstchar(ch) (is_alpha(ch) || (ch) == '_')217218/* Forward references */219char *ppdirforward();220char *ppdirbackward();221char *skipspace();222char *scanstring();223int writeblanks();224int test1();225int convert1();226227/* The main program */228int229main(argc, argv)230int argc;231char *argv[];232{ FILE *in = stdin;233FILE *out = stdout;234char *filename = 0;235char *program_name = argv[0];236char *output_name = 0;237#define bufsize 5000 /* arbitrary size */238char *buf;239char *line;240char *more;241char *usage =242"Usage: ansi2knr [--filename FILENAME] [INPUT_FILE [OUTPUT_FILE]]\n";243/*244* In previous versions, ansi2knr recognized a --varargs switch.245* If this switch was supplied, ansi2knr would attempt to convert246* a ... argument to va_alist and va_dcl; if this switch was not247* supplied, ansi2knr would simply drop any such arguments.248* Now, ansi2knr always does this conversion, and we only249* check for this switch for backward compatibility.250*/251int convert_varargs = 1;252int output_error;253254while ( argc > 1 && argv[1][0] == '-' ) {255if ( !strcmp(argv[1], "--varargs") ) {256convert_varargs = 1;257argc--;258argv++;259continue;260}261if ( !strcmp(argv[1], "--filename") && argc > 2 ) {262filename = argv[2];263argc -= 2;264argv += 2;265continue;266}267fprintf(stderr, "%s: Unrecognized switch: %s\n", program_name,268argv[1]);269fprintf(stderr, usage);270exit(1);271}272switch ( argc )273{274default:275fprintf(stderr, usage);276exit(0);277case 3:278output_name = argv[2];279out = fopen(output_name, "w");280if ( out == NULL ) {281fprintf(stderr, "%s: Cannot open output file %s\n",282program_name, output_name);283exit(1);284}285/* falls through */286case 2:287in = fopen(argv[1], "r");288if ( in == NULL ) {289fprintf(stderr, "%s: Cannot open input file %s\n",290program_name, argv[1]);291exit(1);292}293if ( filename == 0 )294filename = argv[1];295/* falls through */296case 1:297break;298}299if ( filename )300fprintf(out, "#line 1 \"%s\"\n", filename);301buf = malloc(bufsize);302if ( buf == NULL )303{304fprintf(stderr, "Unable to allocate read buffer!\n");305exit(1);306}307line = buf;308while ( fgets(line, (unsigned)(buf + bufsize - line), in) != NULL )309{310test: line += strlen(line);311switch ( test1(buf) )312{313case 2: /* a function header */314convert1(buf, out, 1, convert_varargs);315break;316case 1: /* a function */317/* Check for a { at the start of the next line. */318more = ++line;319f: if ( line >= buf + (bufsize - 1) ) /* overflow check */320goto wl;321if ( fgets(line, (unsigned)(buf + bufsize - line), in) == NULL )322goto wl;323switch ( *skipspace(ppdirforward(more), 1) )324{325case '{':326/* Definitely a function header. */327convert1(buf, out, 0, convert_varargs);328fputs(more, out);329break;330case 0:331/* The next line was blank or a comment: */332/* keep scanning for a non-comment. */333line += strlen(line);334goto f;335default:336/* buf isn't a function header, but */337/* more might be. */338fputs(buf, out);339strcpy(buf, more);340line = buf;341goto test;342}343break;344case -1: /* maybe the start of a function */345if ( line != buf + (bufsize - 1) ) /* overflow check */346continue;347/* falls through */348default: /* not a function */349wl: fputs(buf, out);350break;351}352line = buf;353}354if ( line != buf )355fputs(buf, out);356free(buf);357if ( output_name ) {358output_error = ferror(out);359output_error |= fclose(out);360} else { /* out == stdout */361fflush(out);362output_error = ferror(out);363}364if ( output_error ) {365fprintf(stderr, "%s: error writing to %s\n", program_name,366(output_name ? output_name : "stdout"));367exit(1);368}369if ( in != stdin )370fclose(in);371return 0;372}373374/*375* Skip forward or backward over one or more preprocessor directives.376*/377char *378ppdirforward(p)379char *p;380{381for (; *p == '#'; ++p) {382for (; *p != '\r' && *p != '\n'; ++p)383if (*p == 0)384return p;385if (*p == '\r' && p[1] == '\n')386++p;387}388return p;389}390char *391ppdirbackward(p, limit)392char *p;393char *limit;394{395char *np = p;396397for (;; p = --np) {398if (*np == '\n' && np[-1] == '\r')399--np;400for (; np > limit && np[-1] != '\r' && np[-1] != '\n'; --np)401if (np[-1] == 0)402return np;403if (*np != '#')404return p;405}406}407408/*409* Skip over whitespace, comments, and preprocessor directives,410* in either direction.411*/412char *413skipspace(p, dir)414char *p;415int dir; /* 1 for forward, -1 for backward */416{417for ( ; ; ) {418while ( is_space(*p) )419p += dir;420if ( !(*p == '/' && p[dir] == '*') )421break;422p += dir; p += dir;423while ( !(*p == '*' && p[dir] == '/') ) {424if ( *p == 0 )425return p; /* multi-line comment?? */426p += dir;427}428p += dir; p += dir;429}430return p;431}432433/* Scan over a quoted string, in either direction. */434char *435scanstring(p, dir)436char *p;437int dir;438{439for (p += dir; ; p += dir)440if (*p == '"' && p[-dir] != '\\')441return p + dir;442}443444/*445* Write blanks over part of a string.446* Don't overwrite end-of-line characters.447*/448int449writeblanks(start, end)450char *start;451char *end;452{ char *p;453for ( p = start; p < end; p++ )454if ( *p != '\r' && *p != '\n' )455*p = ' ';456return 0;457}458459/*460* Test whether the string in buf is a function definition.461* The string may contain and/or end with a newline.462* Return as follows:463* 0 - definitely not a function definition;464* 1 - definitely a function definition;465* 2 - definitely a function prototype (NOT USED);466* -1 - may be the beginning of a function definition,467* append another line and look again.468* The reason we don't attempt to convert function prototypes is that469* Ghostscript's declaration-generating macros look too much like470* prototypes, and confuse the algorithms.471*/472int473test1(buf)474char *buf;475{ char *p = buf;476char *bend;477char *endfn;478int contin;479480if ( !isidfirstchar(*p) )481return 0; /* no name at left margin */482bend = skipspace(ppdirbackward(buf + strlen(buf) - 1, buf), -1);483switch ( *bend )484{485case ';': contin = 0 /*2*/; break;486case ')': contin = 1; break;487case '{': return 0; /* not a function */488case '}': return 0; /* not a function */489default: contin = -1;490}491while ( isidchar(*p) )492p++;493endfn = p;494p = skipspace(p, 1);495if ( *p++ != '(' )496return 0; /* not a function */497p = skipspace(p, 1);498if ( *p == ')' )499return 0; /* no parameters */500/* Check that the apparent function name isn't a keyword. */501/* We only need to check for keywords that could be followed */502/* by a left parenthesis (which, unfortunately, is most of them). */503{ static char *words[] =504{ "asm", "auto", "case", "char", "const", "double",505"extern", "float", "for", "if", "int", "long",506"register", "return", "short", "signed", "sizeof",507"static", "switch", "typedef", "unsigned",508"void", "volatile", "while", 0509};510char **key = words;511char *kp;512unsigned len = endfn - buf;513514while ( (kp = *key) != 0 )515{ if ( strlen(kp) == len && !strncmp(kp, buf, len) )516return 0; /* name is a keyword */517key++;518}519}520{521char *id = p;522int len;523/*524* Check for identifier1(identifier2) and not525* identifier1(void), or identifier1(identifier2, xxxx).526*/527528while ( isidchar(*p) )529p++;530len = p - id;531p = skipspace(p, 1);532if (*p == ',' ||533(*p == ')' && (len != 4 || strncmp(id, "void", 4)))534)535return 0; /* not a function */536}537/*538* If the last significant character was a ), we need to count539* parentheses, because it might be part of a formal parameter540* that is a procedure.541*/542if (contin > 0) {543int level = 0;544545for (p = skipspace(buf, 1); *p; p = skipspace(p + 1, 1))546level += (*p == '(' ? 1 : *p == ')' ? -1 : 0);547if (level > 0)548contin = -1;549}550return contin;551}552553/* Convert a recognized function definition or header to K&R syntax. */554int555convert1(buf, out, header, convert_varargs)556char *buf;557FILE *out;558int header; /* Boolean */559int convert_varargs; /* Boolean */560{ char *endfn;561char *p;562/*563* The breaks table contains pointers to the beginning and end564* of each argument.565*/566char **breaks;567unsigned num_breaks = 2; /* for testing */568char **btop;569char **bp;570char **ap;571char *vararg = 0;572573/* Pre-ANSI implementations don't agree on whether strchr */574/* is called strchr or index, so we open-code it here. */575for ( endfn = buf; *(endfn++) != '('; )576;577top: p = endfn;578breaks = (char **)malloc(sizeof(char *) * num_breaks * 2);579if ( breaks == NULL )580{ /* Couldn't allocate break table, give up */581fprintf(stderr, "Unable to allocate break table!\n");582fputs(buf, out);583return -1;584}585btop = breaks + num_breaks * 2 - 2;586bp = breaks;587/* Parse the argument list */588do589{ int level = 0;590char *lp = NULL;591char *rp = NULL;592char *end = NULL;593594if ( bp >= btop )595{ /* Filled up break table. */596/* Allocate a bigger one and start over. */597free((char *)breaks);598num_breaks <<= 1;599goto top;600}601*bp++ = p;602/* Find the end of the argument */603for ( ; end == NULL; p++ )604{ switch(*p)605{606case ',':607if ( !level ) end = p;608break;609case '(':610if ( !level ) lp = p;611level++;612break;613case ')':614if ( --level < 0 ) end = p;615else rp = p;616break;617case '/':618if (p[1] == '*')619p = skipspace(p, 1) - 1;620break;621case '"':622p = scanstring(p, 1) - 1;623break;624default:625;626}627}628/* Erase any embedded prototype parameters. */629if ( lp && rp )630writeblanks(lp + 1, rp);631p--; /* back up over terminator */632/* Find the name being declared. */633/* This is complicated because of procedure and */634/* array modifiers. */635for ( ; ; )636{ p = skipspace(p - 1, -1);637switch ( *p )638{639case ']': /* skip array dimension(s) */640case ')': /* skip procedure args OR name */641{ int level = 1;642while ( level )643switch ( *--p )644{645case ']': case ')':646level++;647break;648case '[': case '(':649level--;650break;651case '/':652if (p > buf && p[-1] == '*')653p = skipspace(p, -1) + 1;654break;655case '"':656p = scanstring(p, -1) + 1;657break;658default: ;659}660}661if ( *p == '(' && *skipspace(p + 1, 1) == '*' )662{ /* We found the name being declared */663while ( !isidfirstchar(*p) )664p = skipspace(p, 1) + 1;665goto found;666}667break;668default:669goto found;670}671}672found: if ( *p == '.' && p[-1] == '.' && p[-2] == '.' )673{ if ( convert_varargs )674{ *bp++ = "va_alist";675vararg = p-2;676}677else678{ p++;679if ( bp == breaks + 1 ) /* sole argument */680writeblanks(breaks[0], p);681else682writeblanks(bp[-1] - 1, p);683bp--;684}685}686else687{ while ( isidchar(*p) ) p--;688*bp++ = p+1;689}690p = end;691}692while ( *p++ == ',' );693*bp = p;694/* Make a special check for 'void' arglist */695if ( bp == breaks+2 )696{ p = skipspace(breaks[0], 1);697if ( !strncmp(p, "void", 4) )698{ p = skipspace(p+4, 1);699if ( p == breaks[2] - 1 )700{ bp = breaks; /* yup, pretend arglist is empty */701writeblanks(breaks[0], p + 1);702}703}704}705/* Put out the function name and left parenthesis. */706p = buf;707while ( p != endfn ) putc(*p, out), p++;708/* Put out the declaration. */709if ( header )710{ fputs(");", out);711for ( p = breaks[0]; *p; p++ )712if ( *p == '\r' || *p == '\n' )713putc(*p, out);714}715else716{ for ( ap = breaks+1; ap < bp; ap += 2 )717{ p = *ap;718while ( isidchar(*p) )719putc(*p, out), p++;720if ( ap < bp - 1 )721fputs(", ", out);722}723fputs(") ", out);724/* Put out the argument declarations */725for ( ap = breaks+2; ap <= bp; ap += 2 )726(*ap)[-1] = ';';727if ( vararg != 0 )728{ *vararg = 0;729fputs(breaks[0], out); /* any prior args */730fputs("va_dcl", out); /* the final arg */731fputs(bp[0], out);732}733else734fputs(breaks[0], out);735}736free((char *)breaks);737return 0;738}739740741