ansi2knr.c
上传用户:zlh9724
上传日期:2007-01-04
资源大小:1991k
文件大小:17k
源码类别:

浏览器

开发平台:

Unix_Linux

  1. /* Copyright (C) 1989, 1991, 1993 Aladdin Enterprises. All rights reserved. */
  2. /* ansi2knr.c */
  3. /* Convert ANSI function declarations to K&R syntax */
  4. /*
  5. ansi2knr is distributed in the hope that it will be useful, but WITHOUT ANY
  6. WARRANTY.  No author or distributor accepts responsibility to anyone for the
  7. consequences of using it or for whether it serves any particular purpose or
  8. works at all, unless he says so in writing.  Refer to the GNU General Public
  9. License (the "GPL") for full details.
  10. Everyone is granted permission to copy, modify and redistribute ansi2knr,
  11. but only under the conditions described in the GPL.  A copy of this license
  12. is supposed to have been given to you along with ansi2knr so you can know
  13. your rights and responsibilities.  It should be in a file named COPYLEFT.
  14. [In the IJG distribution, the GPL appears below, not in a separate file.]
  15. Among other things, the copyright notice and this notice must be preserved
  16. on all copies.
  17. We explicitly state here what we believe is already implied by the GPL: if
  18. the ansi2knr program is distributed as a separate set of sources and a
  19. separate executable file which are aggregated on a storage medium together
  20. with another program, this in itself does not bring the other program under
  21. the GPL, nor does the mere fact that such a program or the procedures for
  22. constructing it invoke the ansi2knr executable bring any other part of the
  23. program under the GPL.
  24. */
  25. /*
  26. ---------- Here is the GNU GPL file COPYING, referred to above ----------
  27. ----- These terms do NOT apply to the JPEG software itself; see README ------
  28.     GHOSTSCRIPT GENERAL PUBLIC LICENSE
  29.     (Clarified 11 Feb 1988)
  30.  Copyright (C) 1988 Richard M. Stallman
  31.  Everyone is permitted to copy and distribute verbatim copies of this
  32.  license, but changing it is not allowed.  You can also use this wording
  33.  to make the terms for other programs.
  34.   The license agreements of most software companies keep you at the
  35. mercy of those companies.  By contrast, our general public license is
  36. intended to give everyone the right to share Ghostscript.  To make sure
  37. that you get the rights we want you to have, we need to make
  38. restrictions that forbid anyone to deny you these rights or to ask you
  39. to surrender the rights.  Hence this license agreement.
  40.   Specifically, we want to make sure that you have the right to give
  41. away copies of Ghostscript, that you receive source code or else can get
  42. it if you want it, that you can change Ghostscript or use pieces of it
  43. in new free programs, and that you know you can do these things.
  44.   To make sure that everyone has such rights, we have to forbid you to
  45. deprive anyone else of these rights.  For example, if you distribute
  46. copies of Ghostscript, you must give the recipients all the rights that
  47. you have.  You must make sure that they, too, receive or can get the
  48. source code.  And you must tell them their rights.
  49.   Also, for our own protection, we must make certain that everyone finds
  50. out that there is no warranty for Ghostscript.  If Ghostscript is
  51. modified by someone else and passed on, we want its recipients to know
  52. that what they have is not what we distributed, so that any problems
  53. introduced by others will not reflect on our reputation.
  54.   Therefore we (Richard M. Stallman and the Free Software Foundation,
  55. Inc.) make the following terms which say what you must do to be allowed
  56. to distribute or change Ghostscript.
  57. COPYING POLICIES
  58.   1. You may copy and distribute verbatim copies of Ghostscript source
  59. code as you receive it, in any medium, provided that you conspicuously
  60. and appropriately publish on each copy a valid copyright and license
  61. notice "Copyright (C) 1989 Aladdin Enterprises.  All rights reserved.
  62. Distributed by Free Software Foundation, Inc." (or with whatever year is
  63. appropriate); keep intact the notices on all files that refer to this
  64. License Agreement and to the absence of any warranty; and give any other
  65. recipients of the Ghostscript program a copy of this License Agreement
  66. along with the program.  You may charge a distribution fee for the
  67. physical act of transferring a copy.
  68.   2. You may modify your copy or copies of Ghostscript or any portion of
  69. it, and copy and distribute such modifications under the terms of
  70. Paragraph 1 above, provided that you also do the following:
  71.     a) cause the modified files to carry prominent notices stating
  72.     that you changed the files and the date of any change; and
  73.     b) cause the whole of any work that you distribute or publish,
  74.     that in whole or in part contains or is a derivative of Ghostscript
  75.     or any part thereof, to be licensed at no charge to all third
  76.     parties on terms identical to those contained in this License
  77.     Agreement (except that you may choose to grant more extensive
  78.     warranty protection to some or all third parties, at your option).
  79.     c) You may charge a distribution fee for the physical act of
  80.     transferring a copy, and you may at your option offer warranty
  81.     protection in exchange for a fee.
  82. Mere aggregation of another unrelated program with this program (or its
  83. derivative) on a volume of a storage or distribution medium does not bring
  84. the other program under the scope of these terms.
  85.   3. You may copy and distribute Ghostscript (or a portion or derivative
  86. of it, under Paragraph 2) in object code or executable form under the
  87. terms of Paragraphs 1 and 2 above provided that you also do one of the
  88. following:
  89.     a) accompany it with the complete corresponding machine-readable
  90.     source code, which must be distributed under the terms of
  91.     Paragraphs 1 and 2 above; or,
  92.     b) accompany it with a written offer, valid for at least three
  93.     years, to give any third party free (except for a nominal
  94.     shipping charge) a complete machine-readable copy of the
  95.     corresponding source code, to be distributed under the terms of
  96.     Paragraphs 1 and 2 above; or,
  97.     c) accompany it with the information you received as to where the
  98.     corresponding source code may be obtained.  (This alternative is
  99.     allowed only for noncommercial distribution and only if you
  100.     received the program in object code or executable form alone.)
  101. For an executable file, complete source code means all the source code for
  102. all modules it contains; but, as a special exception, it need not include
  103. source code for modules which are standard libraries that accompany the
  104. operating system on which the executable file runs.
  105.   4. You may not copy, sublicense, distribute or transfer Ghostscript
  106. except as expressly provided under this License Agreement.  Any attempt
  107. otherwise to copy, sublicense, distribute or transfer Ghostscript is
  108. void and your rights to use the program under this License agreement
  109. shall be automatically terminated.  However, parties who have received
  110. computer software programs from you with this License Agreement will not
  111. have their licenses terminated so long as such parties remain in full
  112. compliance.
  113.   5. If you wish to incorporate parts of Ghostscript into other free
  114. programs whose distribution conditions are different, write to the Free
  115. Software Foundation at 675 Mass Ave, Cambridge, MA 02139.  We have not
  116. yet worked out a simple rule that can be stated here, but we will often
  117. permit this.  We will be guided by the two goals of preserving the free
  118. status of all derivatives of our free software and of promoting the
  119. sharing and reuse of software.
  120. Your comments and suggestions about our licensing policies and our
  121. software are welcome!  Please contact the Free Software Foundation,
  122. Inc., 675 Mass Ave, Cambridge, MA 02139, or call (617) 876-3296.
  123.        NO WARRANTY
  124.   BECAUSE GHOSTSCRIPT IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
  125. NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
  126. WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC, RICHARD
  127. M. STALLMAN, ALADDIN ENTERPRISES, L. PETER DEUTSCH, AND/OR OTHER PARTIES
  128. PROVIDE GHOSTSCRIPT "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
  129. EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  130. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE
  131. ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF GHOSTSCRIPT IS WITH
  132. YOU.  SHOULD GHOSTSCRIPT PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
  133. NECESSARY SERVICING, REPAIR OR CORRECTION.
  134.   IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
  135. STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., L. PETER DEUTSCH, ALADDIN
  136. ENTERPRISES, AND/OR ANY OTHER PARTY WHO MAY MODIFY AND REDISTRIBUTE
  137. GHOSTSCRIPT AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING
  138. ANY LOST PROFITS, LOST MONIES, OR OTHER SPECIAL, INCIDENTAL OR
  139. CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
  140. (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
  141. INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR A FAILURE OF THE
  142. PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) GHOSTSCRIPT, EVEN IF YOU
  143. HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR ANY CLAIM
  144. BY ANY OTHER PARTY.
  145. -------------------- End of file COPYING ------------------------------
  146. */
  147. #include <stdio.h>
  148. #include <ctype.h>
  149. #ifdef BSD
  150. #include <strings.h>
  151. #else
  152. #ifdef VMS
  153. extern int strlen(), strncmp();
  154. #else
  155. #include <string.h>
  156. #endif
  157. #endif
  158. /* malloc and free should be declared in stdlib.h, */
  159. /* but if you've got a K&R compiler, they probably aren't. */
  160. #ifdef MSDOS
  161. #include <malloc.h>
  162. #else
  163. #ifdef VMS
  164.      extern char *malloc();
  165.      extern void free();
  166. #else
  167.      extern char *malloc();
  168.      extern int free();
  169. #endif
  170. #endif
  171. /* Usage:
  172. ansi2knr input_file [output_file]
  173.  * If no output_file is supplied, output goes to stdout.
  174.  * There are no error messages.
  175.  *
  176.  * ansi2knr recognizes functions by seeing a non-keyword identifier
  177.  * at the left margin, followed by a left parenthesis,
  178.  * with a right parenthesis as the last character on the line.
  179.  * It will recognize a multi-line header provided that the last character
  180.  * of the last line of the header is a right parenthesis,
  181.  * and no intervening line ends with a left brace or a semicolon.
  182.  * These algorithms ignore whitespace and comments, except that
  183.  * the function name must be the first thing on the line.
  184.  * The following constructs will confuse it:
  185.  * - Any other construct that starts at the left margin and
  186.  *     follows the above syntax (such as a macro or function call).
  187.  * - Macros that tinker with the syntax of the function header.
  188.  */
  189. /* Scanning macros */
  190. #define isidchar(ch) (isalnum(ch) || (ch) == '_')
  191. #define isidfirstchar(ch) (isalpha(ch) || (ch) == '_')
  192. /* Forward references */
  193. char *skipspace();
  194. int writeblanks();
  195. int test1();
  196. int convert1();
  197. /* The main program */
  198. main(argc, argv)
  199.     int argc;
  200.     char *argv[];
  201. { FILE *in, *out;
  202. #define bufsize 5000 /* arbitrary size */
  203. char *buf;
  204. char *line;
  205. switch ( argc )
  206.    {
  207. default:
  208. printf("Usage: ansi2knr input_file [output_file]n");
  209. exit(0);
  210. case 2:
  211. out = stdout; break;
  212. case 3:
  213. out = fopen(argv[2], "w");
  214. if ( out == NULL )
  215.    { fprintf(stderr, "Cannot open %sn", argv[2]);
  216. exit(1);
  217.    }
  218.    }
  219. in = fopen(argv[1], "r");
  220. if ( in == NULL )
  221.    { fprintf(stderr, "Cannot open %sn", argv[1]);
  222. exit(1);
  223.    }
  224. fprintf(out, "#line 1 "%s"n", argv[1]);
  225. buf = malloc(bufsize);
  226. line = buf;
  227. while ( fgets(line, (unsigned)(buf + bufsize - line), in) != NULL )
  228.    { switch ( test1(buf) )
  229.    {
  230. case 1: /* a function */
  231. convert1(buf, out);
  232. break;
  233. case -1: /* maybe the start of a function */
  234. line = buf + strlen(buf);
  235. if ( line != buf + (bufsize - 1) ) /* overflow check */
  236. continue;
  237. /* falls through */
  238. default: /* not a function */
  239. fputs(buf, out);
  240. break;
  241.    }
  242. line = buf;
  243.    }
  244. if ( line != buf ) fputs(buf, out);
  245. free(buf);
  246. fclose(out);
  247. fclose(in);
  248. return 0;
  249. }
  250. /* Skip over space and comments, in either direction. */
  251. char *
  252. skipspace(p, dir)
  253.     register char *p;
  254.     register int dir; /* 1 for forward, -1 for backward */
  255. { for ( ; ; )
  256.    { while ( isspace(*p) ) p += dir;
  257. if ( !(*p == '/' && p[dir] == '*') ) break;
  258. p += dir;  p += dir;
  259. while ( !(*p == '*' && p[dir] == '/') )
  260.    { if ( *p == 0 ) return p; /* multi-line comment?? */
  261. p += dir;
  262.    }
  263. p += dir;  p += dir;
  264.    }
  265. return p;
  266. }
  267. /*
  268.  * Write blanks over part of a string.
  269.  */
  270. int
  271. writeblanks(start, end)
  272.     char *start;
  273.     char *end;
  274. { char *p;
  275. for ( p = start; p < end; p++ ) *p = ' ';
  276. return 0;
  277. }
  278. /*
  279.  * Test whether the string in buf is a function definition.
  280.  * The string may contain and/or end with a newline.
  281.  * Return as follows:
  282.  * 0 - definitely not a function definition;
  283.  * 1 - definitely a function definition;
  284.  * -1 - may be the beginning of a function definition,
  285.  * append another line and look again.
  286.  */
  287. int
  288. test1(buf)
  289.     char *buf;
  290. { register char *p = buf;
  291. char *bend;
  292. char *endfn;
  293. int contin;
  294. if ( !isidfirstchar(*p) )
  295. return 0; /* no name at left margin */
  296. bend = skipspace(buf + strlen(buf) - 1, -1);
  297. switch ( *bend )
  298.    {
  299. case ')': contin = 1; break;
  300. case '{':
  301. case ';': return 0; /* not a function */
  302. default: contin = -1;
  303.    }
  304. while ( isidchar(*p) ) p++;
  305. endfn = p;
  306. p = skipspace(p, 1);
  307. if ( *p++ != '(' )
  308. return 0; /* not a function */
  309. p = skipspace(p, 1);
  310. if ( *p == ')' )
  311. return 0; /* no parameters */
  312. /* Check that the apparent function name isn't a keyword. */
  313. /* We only need to check for keywords that could be followed */
  314. /* by a left parenthesis (which, unfortunately, is most of them). */
  315.    { static char *words[] =
  316.    { "asm", "auto", "case", "char", "const", "double",
  317. "extern", "float", "for", "if", "int", "long",
  318. "register", "return", "short", "signed", "sizeof",
  319. "static", "switch", "typedef", "unsigned",
  320. "void", "volatile", "while", 0
  321.    };
  322. char **key = words;
  323. char *kp;
  324. int len = endfn - buf;
  325. while ( (kp = *key) != 0 )
  326.    { if ( strlen(kp) == len && !strncmp(kp, buf, len) )
  327. return 0; /* name is a keyword */
  328. key++;
  329.    }
  330.    }
  331. return contin;
  332. }
  333. int
  334. convert1(buf, out)
  335.     char *buf;
  336.     FILE *out;
  337. { char *endfn;
  338. register char *p;
  339. char **breaks;
  340. unsigned num_breaks = 2; /* for testing */
  341. char **btop;
  342. char **bp;
  343. char **ap;
  344. /* Pre-ANSI implementations don't agree on whether strchr */
  345. /* is called strchr or index, so we open-code it here. */
  346. for ( endfn = buf; *(endfn++) != '('; ) ;
  347. top: p = endfn;
  348. breaks = (char **)malloc(sizeof(char *) * num_breaks * 2);
  349. if ( breaks == 0 )
  350.    { /* Couldn't allocate break table, give up */
  351. fprintf(stderr, "Unable to allocate break table!n");
  352. fputs(buf, out);
  353. return -1;
  354.    }
  355. btop = breaks + num_breaks * 2 - 2;
  356. bp = breaks;
  357. /* Parse the argument list */
  358. do
  359.    { int level = 0;
  360. char *end = NULL;
  361. if ( bp >= btop )
  362.    { /* Filled up break table. */
  363. /* Allocate a bigger one and start over. */
  364. free((char *)breaks);
  365. num_breaks <<= 1;
  366. goto top;
  367.    }
  368. *bp++ = p;
  369. /* Find the end of the argument */
  370. for ( ; end == NULL; p++ )
  371.    { switch(*p)
  372.    {
  373. case ',': if ( !level ) end = p; break;
  374. case '(': level++; break;
  375. case ')': if ( --level < 0 ) end = p; break;
  376. case '/': p = skipspace(p, 1) - 1; break;
  377. default: ;
  378.    }
  379.    }
  380. p--; /* back up over terminator */
  381. /* Find the name being declared. */
  382. /* This is complicated because of procedure and */
  383. /* array modifiers. */
  384. for ( ; ; )
  385.    { p = skipspace(p - 1, -1);
  386. switch ( *p )
  387.    {
  388. case ']': /* skip array dimension(s) */
  389. case ')': /* skip procedure args OR name */
  390.    { int level = 1;
  391. while ( level )
  392.  switch ( *--p )
  393.    {
  394. case ']': case ')': level++; break;
  395. case '[': case '(': level--; break;
  396. case '/': p = skipspace(p, -1) + 1; break;
  397. default: ;
  398.    }
  399.    }
  400. if ( *p == '(' && *skipspace(p + 1, 1) == '*' )
  401.    { /* We found the name being declared */
  402. while ( !isidfirstchar(*p) )
  403. p = skipspace(p, 1) + 1;
  404. goto found;
  405.    }
  406. break;
  407. default: goto found;
  408.    }
  409.    }
  410. found: if ( *p == '.' && p[-1] == '.' && p[-2] == '.' )
  411.    { p++;
  412. if ( bp == breaks + 1 ) /* sole argument */
  413. writeblanks(breaks[0], p);
  414. else
  415. writeblanks(bp[-1] - 1, p);
  416. bp--;
  417.    }
  418. else
  419.    { while ( isidchar(*p) ) p--;
  420. *bp++ = p+1;
  421.    }
  422. p = end;
  423.    }
  424. while ( *p++ == ',' );
  425. *bp = p;
  426. /* Make a special check for 'void' arglist */
  427. if ( bp == breaks+2 )
  428.    { p = skipspace(breaks[0], 1);
  429. if ( !strncmp(p, "void", 4) )
  430.    { p = skipspace(p+4, 1);
  431. if ( p == breaks[2] - 1 )
  432.    { bp = breaks; /* yup, pretend arglist is empty */
  433. writeblanks(breaks[0], p + 1);
  434.    }
  435.    }
  436.    }
  437. /* Put out the function name */
  438. p = buf;
  439. while ( p != endfn ) putc(*p, out), p++;
  440. /* Put out the declaration */
  441. for ( ap = breaks+1; ap < bp; ap += 2 )
  442.    { p = *ap;
  443. while ( isidchar(*p) ) putc(*p, out), p++;
  444. if ( ap < bp - 1 ) fputs(", ", out);
  445.    }
  446. fputs(")  ", out);
  447. /* Put out the argument declarations */
  448. for ( ap = breaks+2; ap <= bp; ap += 2 ) (*ap)[-1] = ';';
  449. fputs(breaks[0], out);
  450. free((char *)breaks);
  451. return 0;
  452. }