]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/indent/indent.c
This commit was generated by cvs2svn to compensate for changes in r162012,
[FreeBSD/FreeBSD.git] / usr.bin / indent / indent.c
1 /*
2  * Copyright (c) 1985 Sun Microsystems, Inc.
3  * Copyright (c) 1976 Board of Trustees of the University of Illinois.
4  * Copyright (c) 1980, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *      This product includes software developed by the University of
18  *      California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35
36 #ifndef lint
37 static const char copyright[] =
38 "@(#) Copyright (c) 1985 Sun Microsystems, Inc.\n\
39 @(#) Copyright (c) 1976 Board of Trustees of the University of Illinois.\n\
40 @(#) Copyright (c) 1980, 1993\n\
41         The Regents of the University of California.  All rights reserved.\n";
42 #endif /* not lint */
43
44 #if 0
45 #ifndef lint
46 static char sccsid[] = "@(#)indent.c    5.17 (Berkeley) 6/7/93";
47 #endif /* not lint */
48 #endif
49
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
52
53 #include <sys/param.h>
54 #include <err.h>
55 #include <fcntl.h>
56 #include <unistd.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <ctype.h>
61 #include "indent_globs.h"
62 #include "indent_codes.h"
63 #include "indent.h"
64
65 static void bakcopy(void);
66
67 const char *in_name = "Standard Input"; /* will always point to name of input
68                                          * file */
69 const char *out_name = "Standard Output";       /* will always point to name
70                                                  * of output file */
71 char        bakfile[MAXPATHLEN] = "";
72
73 int
74 main(int argc, char **argv)
75 {
76
77     int         dec_ind;        /* current indentation for declarations */
78     int         di_stack[20];   /* a stack of structure indentation levels */
79     int         flushed_nl;     /* used when buffering up comments to remember
80                                  * that a newline was passed over */
81     int         force_nl;       /* when true, code must be broken */
82     int         hd_type = 0;    /* used to store type of stmt for if (...),
83                                  * for (...), etc */
84     int         i;              /* local loop counter */
85     int         scase;          /* set to true when we see a case, so we will
86                                  * know what to do with the following colon */
87     int         sp_sw;          /* when true, we are in the expression of
88                                  * if(...), while(...), etc. */
89     int         squest;         /* when this is positive, we have seen a ?
90                                  * without the matching : in a <c>?<s>:<s>
91                                  * construct */
92     const char *t_ptr;          /* used for copying tokens */
93     int         tabs_to_var;    /* true if using tabs to indent to var name */
94     int         type_code;      /* the type of token, returned by lexi */
95
96     int         last_else = 0;  /* true iff last keyword was an else */
97
98
99     /*-----------------------------------------------*\
100     |                 INITIALIZATION                  |
101     \*-----------------------------------------------*/
102
103     found_err = 0;
104
105     ps.p_stack[0] = stmt;       /* this is the parser's stack */
106     ps.last_nl = true;          /* this is true if the last thing scanned was
107                                  * a newline */
108     ps.last_token = semicolon;
109     combuf = (char *) malloc(bufsize);
110     if (combuf == NULL)
111         err(1, NULL);
112     labbuf = (char *) malloc(bufsize);
113     if (labbuf == NULL)
114         err(1, NULL);
115     codebuf = (char *) malloc(bufsize);
116     if (codebuf == NULL)
117         err(1, NULL);
118     tokenbuf = (char *) malloc(bufsize);
119     if (tokenbuf == NULL)
120         err(1, NULL);
121     l_com = combuf + bufsize - 5;
122     l_lab = labbuf + bufsize - 5;
123     l_code = codebuf + bufsize - 5;
124     l_token = tokenbuf + bufsize - 5;
125     combuf[0] = codebuf[0] = labbuf[0] = ' ';   /* set up code, label, and
126                                                  * comment buffers */
127     combuf[1] = codebuf[1] = labbuf[1] = '\0';
128     ps.else_if = 1;             /* Default else-if special processing to on */
129     s_lab = e_lab = labbuf + 1;
130     s_code = e_code = codebuf + 1;
131     s_com = e_com = combuf + 1;
132     s_token = e_token = tokenbuf + 1;
133
134     in_buffer = (char *) malloc(10);
135     if (in_buffer == NULL)
136         err(1, NULL);
137     in_buffer_limit = in_buffer + 8;
138     buf_ptr = buf_end = in_buffer;
139     line_no = 1;
140     had_eof = ps.in_decl = ps.decl_on_line = break_comma = false;
141     sp_sw = force_nl = false;
142     ps.in_or_st = false;
143     ps.bl_line = true;
144     dec_ind = 0;
145     di_stack[ps.dec_nest = 0] = 0;
146     ps.want_blank = ps.in_stmt = ps.ind_stmt = false;
147
148     scase = ps.pcase = false;
149     squest = 0;
150     sc_end = 0;
151     bp_save = 0;
152     be_save = 0;
153
154     output = 0;
155
156     /*--------------------------------------------------*\
157     |                   COMMAND LINE SCAN                |
158     \*--------------------------------------------------*/
159
160 #ifdef undef
161     max_col = 78;               /* -l78 */
162     lineup_to_parens = 1;       /* -lp */
163     ps.ljust_decl = 0;          /* -ndj */
164     ps.com_ind = 33;            /* -c33 */
165     star_comment_cont = 1;      /* -sc */
166     ps.ind_size = 8;            /* -i8 */
167     verbose = 0;
168     ps.decl_indent = 16;        /* -di16 */
169     ps.local_decl_indent = -1;  /* if this is not set to some nonnegative value
170                                  * by an arg, we will set this equal to
171                                  * ps.decl_ind */
172     ps.indent_parameters = 1;   /* -ip */
173     ps.decl_com_ind = 0;        /* if this is not set to some positive value
174                                  * by an arg, we will set this equal to
175                                  * ps.com_ind */
176     btype_2 = 1;                /* -br */
177     cuddle_else = 1;            /* -ce */
178     ps.unindent_displace = 0;   /* -d0 */
179     ps.case_indent = 0;         /* -cli0 */
180     format_block_comments = 1;  /* -fcb */
181     format_col1_comments = 1;   /* -fc1 */
182     procnames_start_line = 1;   /* -psl */
183     proc_calls_space = 0;       /* -npcs */
184     comment_delimiter_on_blankline = 1; /* -cdb */
185     ps.leave_comma = 1;         /* -nbc */
186 #endif
187
188     for (i = 1; i < argc; ++i)
189         if (strcmp(argv[i], "-npro") == 0)
190             break;
191     set_defaults();
192     if (i >= argc)
193         set_profile();
194
195     for (i = 1; i < argc; ++i) {
196
197         /*
198          * look thru args (if any) for changes to defaults
199          */
200         if (argv[i][0] != '-') {/* no flag on parameter */
201             if (input == 0) {   /* we must have the input file */
202                 in_name = argv[i];      /* remember name of input file */
203                 input = fopen(in_name, "r");
204                 if (input == 0)         /* check for open error */
205                         err(1, "%s", in_name);
206                 continue;
207             }
208             else if (output == 0) {     /* we have the output file */
209                 out_name = argv[i];     /* remember name of output file */
210                 if (strcmp(in_name, out_name) == 0) {   /* attempt to overwrite
211                                                          * the file */
212                     errx(1, "input and output files must be different");
213                 }
214                 output = fopen(out_name, "w");
215                 if (output == 0)        /* check for create error */
216                         err(1, "%s", out_name);
217                 continue;
218             }
219             errx(1, "unknown parameter: %s", argv[i]);
220         }
221         else
222             set_option(argv[i]);
223     }                           /* end of for */
224     if (input == 0)
225         input = stdin;
226     if (output == 0) {
227         if (troff || input == stdin)
228             output = stdout;
229         else {
230             out_name = in_name;
231             bakcopy();
232         }
233     }
234     if (ps.com_ind <= 1)
235         ps.com_ind = 2;         /* dont put normal comments before column 2 */
236     if (troff) {
237         if (bodyf.font[0] == 0)
238             parsefont(&bodyf, "R");
239         if (scomf.font[0] == 0)
240             parsefont(&scomf, "I");
241         if (blkcomf.font[0] == 0)
242             blkcomf = scomf, blkcomf.size += 2;
243         if (boxcomf.font[0] == 0)
244             boxcomf = blkcomf;
245         if (stringf.font[0] == 0)
246             parsefont(&stringf, "L");
247         if (keywordf.font[0] == 0)
248             parsefont(&keywordf, "B");
249         writefdef(&bodyf, 'B');
250         writefdef(&scomf, 'C');
251         writefdef(&blkcomf, 'L');
252         writefdef(&boxcomf, 'X');
253         writefdef(&stringf, 'S');
254         writefdef(&keywordf, 'K');
255     }
256     if (block_comment_max_col <= 0)
257         block_comment_max_col = max_col;
258     if (ps.local_decl_indent < 0)       /* if not specified by user, set this */
259         ps.local_decl_indent = ps.decl_indent;
260     if (ps.decl_com_ind <= 0)   /* if not specified by user, set this */
261         ps.decl_com_ind = ps.ljust_decl ? (ps.com_ind <= 10 ? 2 : ps.com_ind - 8) : ps.com_ind;
262     if (continuation_indent == 0)
263         continuation_indent = ps.ind_size;
264     fill_buffer();              /* get first batch of stuff into input buffer */
265
266     parse(semicolon);
267     {
268         char *p = buf_ptr;
269         int col = 1;
270
271         while (1) {
272             if (*p == ' ')
273                 col++;
274             else if (*p == '\t')
275                 col = ((col - 1) & ~7) + 9;
276             else
277                 break;
278             p++;
279         }
280         if (col > ps.ind_size)
281             ps.ind_level = ps.i_l_follow = col / ps.ind_size;
282     }
283     if (troff) {
284         const char *p = in_name,
285                    *beg = in_name;
286
287         while (*p)
288             if (*p++ == '/')
289                 beg = p;
290         fprintf(output, ".Fn \"%s\"\n", beg);
291     }
292     /*
293      * START OF MAIN LOOP
294      */
295
296     while (1) {                 /* this is the main loop.  it will go until we
297                                  * reach eof */
298         int         is_procname;
299
300         type_code = lexi();     /* lexi reads one token.  The actual
301                                  * characters read are stored in "token". lexi
302                                  * returns a code indicating the type of token */
303         is_procname = ps.procname[0];
304
305         /*
306          * The following code moves everything following an if (), while (),
307          * else, etc. up to the start of the following stmt to a buffer. This
308          * allows proper handling of both kinds of brace placement.
309          */
310
311         flushed_nl = false;
312         while (ps.search_brace) {       /* if we scanned an if(), while(),
313                                          * etc., we might need to copy stuff
314                                          * into a buffer we must loop, copying
315                                          * stuff into save_com, until we find
316                                          * the start of the stmt which follows
317                                          * the if, or whatever */
318             switch (type_code) {
319             case newline:
320                 ++line_no;
321                 flushed_nl = true;
322             case form_feed:
323                 break;          /* form feeds and newlines found here will be
324                                  * ignored */
325
326             case lbrace:        /* this is a brace that starts the compound
327                                  * stmt */
328                 if (sc_end == 0) {      /* ignore buffering if a comment wasnt
329                                          * stored up */
330                     ps.search_brace = false;
331                     goto check_type;
332                 }
333                 if (btype_2) {
334                     save_com[0] = '{';  /* we either want to put the brace
335                                          * right after the if */
336                     goto sw_buffer;     /* go to common code to get out of
337                                          * this loop */
338                 }
339             case comment:       /* we have a comment, so we must copy it into
340                                  * the buffer */
341                 if (!flushed_nl || sc_end != 0) {
342                     if (sc_end == 0) {  /* if this is the first comment, we
343                                          * must set up the buffer */
344                         save_com[0] = save_com[1] = ' ';
345                         sc_end = &(save_com[2]);
346                     }
347                     else {
348                         *sc_end++ = '\n';       /* add newline between
349                                                  * comments */
350                         *sc_end++ = ' ';
351                         --line_no;
352                     }
353                     *sc_end++ = '/';    /* copy in start of comment */
354                     *sc_end++ = '*';
355
356                     for (;;) {  /* loop until we get to the end of the comment */
357                         *sc_end = *buf_ptr++;
358                         if (buf_ptr >= buf_end)
359                             fill_buffer();
360
361                         if (*sc_end++ == '*' && *buf_ptr == '/')
362                             break;      /* we are at end of comment */
363
364                         if (sc_end >= &(save_com[sc_size])) {   /* check for temp buffer
365                                                                  * overflow */
366                             diag2(1, "Internal buffer overflow - Move big comment from right after if, while, or whatever");
367                             fflush(output);
368                             exit(1);
369                         }
370                     }
371                     *sc_end++ = '/';    /* add ending slash */
372                     if (++buf_ptr >= buf_end)   /* get past / in buffer */
373                         fill_buffer();
374                     break;
375                 }
376             default:            /* it is the start of a normal statement */
377                 if (flushed_nl) /* if we flushed a newline, make sure it is
378                                  * put back */
379                     force_nl = true;
380                 if ((type_code == sp_paren && *token == 'i'
381                         && last_else && ps.else_if)
382                         || (type_code == sp_nparen && *token == 'e'
383                         && e_code != s_code && e_code[-1] == '}'))
384                     force_nl = false;
385
386                 if (sc_end == 0) {      /* ignore buffering if comment wasnt
387                                          * saved up */
388                     ps.search_brace = false;
389                     goto check_type;
390                 }
391                 if (force_nl) { /* if we should insert a nl here, put it into
392                                  * the buffer */
393                     force_nl = false;
394                     --line_no;  /* this will be re-increased when the nl is
395                                  * read from the buffer */
396                     *sc_end++ = '\n';
397                     *sc_end++ = ' ';
398                     if (verbose && !flushed_nl) /* print error msg if the line
399                                                  * was not already broken */
400                         diag2(0, "Line broken");
401                     flushed_nl = false;
402                 }
403                 for (t_ptr = token; *t_ptr; ++t_ptr)
404                     *sc_end++ = *t_ptr; /* copy token into temp buffer */
405                 ps.procname[0] = 0;
406
407         sw_buffer:
408                 ps.search_brace = false;        /* stop looking for start of
409                                                  * stmt */
410                 bp_save = buf_ptr;      /* save current input buffer */
411                 be_save = buf_end;
412                 buf_ptr = save_com;     /* fix so that subsequent calls to
413                                          * lexi will take tokens out of
414                                          * save_com */
415                 *sc_end++ = ' ';/* add trailing blank, just in case */
416                 buf_end = sc_end;
417                 sc_end = 0;
418                 break;
419             }                   /* end of switch */
420             if (type_code != 0) /* we must make this check, just in case there
421                                  * was an unexpected EOF */
422                 type_code = lexi();     /* read another token */
423             /* if (ps.search_brace) ps.procname[0] = 0; */
424             if ((is_procname = ps.procname[0]) && flushed_nl
425                     && !procnames_start_line && ps.in_decl
426                     && type_code == ident)
427                 flushed_nl = 0;
428         }                       /* end of while (search_brace) */
429         last_else = 0;
430 check_type:
431         if (type_code == 0) {   /* we got eof */
432             if (s_lab != e_lab || s_code != e_code
433                     || s_com != e_com)  /* must dump end of line */
434                 dump_line();
435             if (ps.tos > 1)     /* check for balanced braces */
436                 diag2(1, "Stuff missing from end of file");
437
438             if (verbose) {
439                 printf("There were %d output lines and %d comments\n",
440                        ps.out_lines, ps.out_coms);
441                 printf("(Lines with comments)/(Lines with code): %6.3f\n",
442                        (1.0 * ps.com_lines) / code_lines);
443             }
444             fflush(output);
445             exit(found_err);
446         }
447         if (
448                 (type_code != comment) &&
449                 (type_code != newline) &&
450                 (type_code != preesc) &&
451                 (type_code != form_feed)) {
452             if (force_nl &&
453                     (type_code != semicolon) &&
454                     (type_code != lbrace || !btype_2)) {
455                 /* we should force a broken line here */
456                 if (verbose && !flushed_nl)
457                     diag2(0, "Line broken");
458                 flushed_nl = false;
459                 dump_line();
460                 ps.want_blank = false;  /* dont insert blank at line start */
461                 force_nl = false;
462             }
463             ps.in_stmt = true;  /* turn on flag which causes an extra level of
464                                  * indentation. this is turned off by a ; or
465                                  * '}' */
466             if (s_com != e_com) {       /* the turkey has embedded a comment
467                                          * in a line. fix it */
468                 *e_code++ = ' ';
469                 for (t_ptr = s_com; *t_ptr; ++t_ptr) {
470                     CHECK_SIZE_CODE;
471                     *e_code++ = *t_ptr;
472                 }
473                 *e_code++ = ' ';
474                 *e_code = '\0'; /* null terminate code sect */
475                 ps.want_blank = false;
476                 e_com = s_com;
477             }
478         }
479         else if (type_code != comment)  /* preserve force_nl thru a comment */
480             force_nl = false;   /* cancel forced newline after newline, form
481                                  * feed, etc */
482
483
484
485         /*-----------------------------------------------------*\
486         |          do switch on type of token scanned           |
487         \*-----------------------------------------------------*/
488         CHECK_SIZE_CODE;
489         switch (type_code) {    /* now, decide what to do with the token */
490
491         case form_feed: /* found a form feed in line */
492             ps.use_ff = true;   /* a form feed is treated much like a newline */
493             dump_line();
494             ps.want_blank = false;
495             break;
496
497         case newline:
498             if (ps.last_token != comma || ps.p_l_follow > 0
499                     || !ps.leave_comma || ps.block_init || !break_comma || s_com != e_com) {
500                 dump_line();
501                 ps.want_blank = false;
502             }
503             ++line_no;          /* keep track of input line number */
504             break;
505
506         case lparen:            /* got a '(' or '[' */
507             ++ps.p_l_follow;    /* count parens to make Healy happy */
508             if (ps.want_blank && *token != '[' &&
509                     (ps.last_token != ident || proc_calls_space
510               || (ps.its_a_keyword && (!ps.sizeof_keyword || Bill_Shannon))))
511                 *e_code++ = ' ';
512             if (ps.in_decl && !ps.block_init)
513                 if (troff && !ps.dumped_decl_indent && !is_procname && ps.last_token == decl) {
514                     ps.dumped_decl_indent = 1;
515                     sprintf(e_code, "\n.Du %dp+\200p \"%s\"\n", dec_ind * 7, token);
516                     e_code += strlen(e_code);
517                 }
518                 else {
519                     while ((e_code - s_code) < dec_ind) {
520                         CHECK_SIZE_CODE;
521                         *e_code++ = ' ';
522                     }
523                     *e_code++ = token[0];
524                 }
525             else
526                 *e_code++ = token[0];
527             ps.paren_indents[ps.p_l_follow - 1] = e_code - s_code;
528             if (sp_sw && ps.p_l_follow == 1 && extra_expression_indent
529                     && ps.paren_indents[0] < 2 * ps.ind_size)
530                 ps.paren_indents[0] = 2 * ps.ind_size;
531             ps.want_blank = false;
532             if (ps.in_or_st && *token == '(' && ps.tos <= 2) {
533                 /*
534                  * this is a kluge to make sure that declarations will be
535                  * aligned right if proc decl has an explicit type on it, i.e.
536                  * "int a(x) {..."
537                  */
538                 parse(semicolon);       /* I said this was a kluge... */
539                 ps.in_or_st = false;    /* turn off flag for structure decl or
540                                          * initialization */
541             }
542             if (ps.sizeof_keyword)
543                 ps.sizeof_mask |= 1 << ps.p_l_follow;
544             break;
545
546         case rparen:            /* got a ')' or ']' */
547             rparen_count--;
548             if (ps.cast_mask & (1 << ps.p_l_follow) & ~ps.sizeof_mask) {
549                 ps.last_u_d = true;
550                 ps.cast_mask &= (1 << ps.p_l_follow) - 1;
551                 ps.want_blank = false;
552             } else
553                 ps.want_blank = true;
554             ps.sizeof_mask &= (1 << ps.p_l_follow) - 1;
555             if (--ps.p_l_follow < 0) {
556                 ps.p_l_follow = 0;
557                 diag3(0, "Extra %c", *token);
558             }
559             if (e_code == s_code)       /* if the paren starts the line */
560                 ps.paren_level = ps.p_l_follow; /* then indent it */
561
562             *e_code++ = token[0];
563
564             if (sp_sw && (ps.p_l_follow == 0)) {        /* check for end of if
565                                                          * (...), or some such */
566                 sp_sw = false;
567                 force_nl = true;/* must force newline after if */
568                 ps.last_u_d = true;     /* inform lexi that a following
569                                          * operator is unary */
570                 ps.in_stmt = false;     /* dont use stmt continuation
571                                          * indentation */
572
573                 parse(hd_type); /* let parser worry about if, or whatever */
574             }
575             ps.search_brace = btype_2;  /* this should insure that constructs
576                                          * such as main(){...} and int[]{...}
577                                          * have their braces put in the right
578                                          * place */
579             break;
580
581         case unary_op:          /* this could be any unary operation */
582             if (ps.want_blank)
583                 *e_code++ = ' ';
584
585             if (troff && !ps.dumped_decl_indent && ps.in_decl && !is_procname) {
586                 sprintf(e_code, "\n.Du %dp+\200p \"%s\"\n", dec_ind * 7, token);
587                 ps.dumped_decl_indent = 1;
588                 e_code += strlen(e_code);
589             }
590             else {
591                 const char *res = token;
592
593                 if (ps.in_decl && !ps.block_init) {     /* if this is a unary op
594                                                          * in a declaration, we
595                                                          * should indent this
596                                                          * token */
597                     for (i = 0; token[i]; ++i); /* find length of token */
598                     while ((e_code - s_code) < (dec_ind - i)) {
599                         CHECK_SIZE_CODE;
600                         *e_code++ = ' ';        /* pad it */
601                     }
602                 }
603                 if (troff && token[0] == '-' && token[1] == '>')
604                     res = "\\(->";
605                 for (t_ptr = res; *t_ptr; ++t_ptr) {
606                     CHECK_SIZE_CODE;
607                     *e_code++ = *t_ptr;
608                 }
609             }
610             ps.want_blank = false;
611             break;
612
613         case binary_op: /* any binary operation */
614             if (ps.want_blank)
615                 *e_code++ = ' ';
616             {
617                 const char *res = token;
618
619                 if (troff)
620                     switch (token[0]) {
621                     case '<':
622                         if (token[1] == '=')
623                             res = "\\(<=";
624                         break;
625                     case '>':
626                         if (token[1] == '=')
627                             res = "\\(>=";
628                         break;
629                     case '!':
630                         if (token[1] == '=')
631                             res = "\\(!=";
632                         break;
633                     case '|':
634                         if (token[1] == '|')
635                             res = "\\(br\\(br";
636                         else if (token[1] == 0)
637                             res = "\\(br";
638                         break;
639                     }
640                 for (t_ptr = res; *t_ptr; ++t_ptr) {
641                     CHECK_SIZE_CODE;
642                     *e_code++ = *t_ptr; /* move the operator */
643                 }
644             }
645             ps.want_blank = true;
646             break;
647
648         case postop:            /* got a trailing ++ or -- */
649             *e_code++ = token[0];
650             *e_code++ = token[1];
651             ps.want_blank = true;
652             break;
653
654         case question:          /* got a ? */
655             squest++;           /* this will be used when a later colon
656                                  * appears so we can distinguish the
657                                  * <c>?<n>:<n> construct */
658             if (ps.want_blank)
659                 *e_code++ = ' ';
660             *e_code++ = '?';
661             ps.want_blank = true;
662             break;
663
664         case casestmt:          /* got word 'case' or 'default' */
665             scase = true;       /* so we can process the later colon properly */
666             goto copy_id;
667
668         case colon:             /* got a ':' */
669             if (squest > 0) {   /* it is part of the <c>?<n>: <n> construct */
670                 --squest;
671                 if (ps.want_blank)
672                     *e_code++ = ' ';
673                 *e_code++ = ':';
674                 ps.want_blank = true;
675                 break;
676             }
677             if (ps.in_decl) {
678                 *e_code++ = ':';
679                 ps.want_blank = false;
680                 break;
681             }
682             ps.in_stmt = false; /* seeing a label does not imply we are in a
683                                  * stmt */
684             for (t_ptr = s_code; *t_ptr; ++t_ptr)
685                 *e_lab++ = *t_ptr;      /* turn everything so far into a label */
686             e_code = s_code;
687             *e_lab++ = ':';
688             *e_lab++ = ' ';
689             *e_lab = '\0';
690
691             force_nl = ps.pcase = scase;        /* ps.pcase will be used by
692                                                  * dump_line to decide how to
693                                                  * indent the label. force_nl
694                                                  * will force a case n: to be
695                                                  * on a line by itself */
696             scase = false;
697             ps.want_blank = false;
698             break;
699
700         case semicolon: /* got a ';' */
701             ps.in_or_st = false;/* we are not in an initialization or
702                                  * structure declaration */
703             scase = false;      /* these will only need resetting in an error */
704             squest = 0;
705             if (ps.last_token == rparen && rparen_count == 0)
706                 ps.in_parameter_declaration = 0;
707             ps.cast_mask = 0;
708             ps.sizeof_mask = 0;
709             ps.block_init = 0;
710             ps.block_init_level = 0;
711             ps.just_saw_decl--;
712
713             if (ps.in_decl && s_code == e_code && !ps.block_init)
714                 while ((e_code - s_code) < (dec_ind - 1)) {
715                     CHECK_SIZE_CODE;
716                     *e_code++ = ' ';
717                 }
718
719             ps.in_decl = (ps.dec_nest > 0);     /* if we were in a first level
720                                                  * structure declaration, we
721                                                  * arent any more */
722
723             if ((!sp_sw || hd_type != forstmt) && ps.p_l_follow > 0) {
724
725                 /*
726                  * This should be true iff there were unbalanced parens in the
727                  * stmt.  It is a bit complicated, because the semicolon might
728                  * be in a for stmt
729                  */
730                 diag2(1, "Unbalanced parens");
731                 ps.p_l_follow = 0;
732                 if (sp_sw) {    /* this is a check for an if, while, etc. with
733                                  * unbalanced parens */
734                     sp_sw = false;
735                     parse(hd_type);     /* dont lose the if, or whatever */
736                 }
737             }
738             *e_code++ = ';';
739             ps.want_blank = true;
740             ps.in_stmt = (ps.p_l_follow > 0);   /* we are no longer in the
741                                                  * middle of a stmt */
742
743             if (!sp_sw) {       /* if not if for (;;) */
744                 parse(semicolon);       /* let parser know about end of stmt */
745                 force_nl = true;/* force newline after an end of stmt */
746             }
747             break;
748
749         case lbrace:            /* got a '{' */
750             ps.in_stmt = false; /* dont indent the {} */
751             if (!ps.block_init)
752                 force_nl = true;/* force other stuff on same line as '{' onto
753                                  * new line */
754             else if (ps.block_init_level <= 0)
755                 ps.block_init_level = 1;
756             else
757                 ps.block_init_level++;
758
759             if (s_code != e_code && !ps.block_init) {
760                 if (!btype_2) {
761                     dump_line();
762                     ps.want_blank = false;
763                 }
764                 else if (ps.in_parameter_declaration && !ps.in_or_st) {
765                     ps.i_l_follow = 0;
766                     if (function_brace_split) { /* dump the line prior to the
767                                                  * brace ... */
768                         dump_line();
769                         ps.want_blank = false;
770                     } else      /* add a space between the decl and brace */
771                         ps.want_blank = true;
772                 }
773             }
774             if (ps.in_parameter_declaration)
775                 prefix_blankline_requested = 0;
776
777             if (ps.p_l_follow > 0) {    /* check for preceding unbalanced
778                                          * parens */
779                 diag2(1, "Unbalanced parens");
780                 ps.p_l_follow = 0;
781                 if (sp_sw) {    /* check for unclosed if, for, etc. */
782                     sp_sw = false;
783                     parse(hd_type);
784                     ps.ind_level = ps.i_l_follow;
785                 }
786             }
787             if (s_code == e_code)
788                 ps.ind_stmt = false;    /* dont put extra indentation on line
789                                          * with '{' */
790             if (ps.in_decl && ps.in_or_st) {    /* this is either a structure
791                                                  * declaration or an init */
792                 di_stack[ps.dec_nest++] = dec_ind;
793                 /* ?            dec_ind = 0; */
794             }
795             else {
796                 ps.decl_on_line = false;        /* we cant be in the middle of
797                                                  * a declaration, so dont do
798                                                  * special indentation of
799                                                  * comments */
800                 if (blanklines_after_declarations_at_proctop
801                         && ps.in_parameter_declaration)
802                     postfix_blankline_requested = 1;
803                 ps.in_parameter_declaration = 0;
804             }
805             dec_ind = 0;
806             parse(lbrace);      /* let parser know about this */
807             if (ps.want_blank)  /* put a blank before '{' if '{' is not at
808                                  * start of line */
809                 *e_code++ = ' ';
810             ps.want_blank = false;
811             *e_code++ = '{';
812             ps.just_saw_decl = 0;
813             break;
814
815         case rbrace:            /* got a '}' */
816             if (ps.p_stack[ps.tos] == decl && !ps.block_init)   /* semicolons can be
817                                                                  * omitted in
818                                                                  * declarations */
819                 parse(semicolon);
820             if (ps.p_l_follow) {/* check for unclosed if, for, else. */
821                 diag2(1, "Unbalanced parens");
822                 ps.p_l_follow = 0;
823                 sp_sw = false;
824             }
825             ps.just_saw_decl = 0;
826             ps.block_init_level--;
827             if (s_code != e_code && !ps.block_init) {   /* '}' must be first on
828                                                          * line */
829                 if (verbose)
830                     diag2(0, "Line broken");
831                 dump_line();
832             }
833             *e_code++ = '}';
834             ps.want_blank = true;
835             ps.in_stmt = ps.ind_stmt = false;
836             if (ps.dec_nest > 0) {      /* we are in multi-level structure
837                                          * declaration */
838                 dec_ind = di_stack[--ps.dec_nest];
839                 if (ps.dec_nest == 0 && !ps.in_parameter_declaration)
840                     ps.just_saw_decl = 2;
841                 ps.in_decl = true;
842             }
843             prefix_blankline_requested = 0;
844             parse(rbrace);      /* let parser know about this */
845             ps.search_brace = cuddle_else && ps.p_stack[ps.tos] == ifhead
846                 && ps.il[ps.tos] >= ps.ind_level;
847             if (ps.tos <= 1 && blanklines_after_procs && ps.dec_nest <= 0)
848                 postfix_blankline_requested = 1;
849             break;
850
851         case swstmt:            /* got keyword "switch" */
852             sp_sw = true;
853             hd_type = swstmt;   /* keep this for when we have seen the
854                                  * expression */
855             goto copy_id;       /* go move the token into buffer */
856
857         case sp_paren:          /* token is if, while, for */
858             sp_sw = true;       /* the interesting stuff is done after the
859                                  * expression is scanned */
860             hd_type = (*token == 'i' ? ifstmt :
861                        (*token == 'w' ? whilestmt : forstmt));
862
863             /*
864              * remember the type of header for later use by parser
865              */
866             goto copy_id;       /* copy the token into line */
867
868         case sp_nparen: /* got else, do */
869             ps.in_stmt = false;
870             if (*token == 'e') {
871                 if (e_code != s_code && (!cuddle_else || e_code[-1] != '}')) {
872                     if (verbose)
873                         diag2(0, "Line broken");
874                     dump_line();/* make sure this starts a line */
875                     ps.want_blank = false;
876                 }
877                 force_nl = true;/* also, following stuff must go onto new line */
878                 last_else = 1;
879                 parse(elselit);
880             }
881             else {
882                 if (e_code != s_code) { /* make sure this starts a line */
883                     if (verbose)
884                         diag2(0, "Line broken");
885                     dump_line();
886                     ps.want_blank = false;
887                 }
888                 force_nl = true;/* also, following stuff must go onto new line */
889                 last_else = 0;
890                 parse(dolit);
891             }
892             goto copy_id;       /* move the token into line */
893
894         case decl:              /* we have a declaration type (int, register,
895                                  * etc.) */
896             parse(decl);        /* let parser worry about indentation */
897             if (ps.last_token == rparen && ps.tos <= 1) {
898                 ps.in_parameter_declaration = 1;
899                 if (s_code != e_code) {
900                     dump_line();
901                     ps.want_blank = 0;
902                 }
903             }
904             if (ps.in_parameter_declaration && ps.indent_parameters && ps.dec_nest == 0) {
905                 ps.ind_level = ps.i_l_follow = 1;
906                 ps.ind_stmt = 0;
907             }
908             ps.in_or_st = true; /* this might be a structure or initialization
909                                  * declaration */
910             ps.in_decl = ps.decl_on_line = true;
911             if ( /* !ps.in_or_st && */ ps.dec_nest <= 0)
912                 ps.just_saw_decl = 2;
913             prefix_blankline_requested = 0;
914             for (i = 0; token[i++];);   /* get length of token */
915
916             if (ps.ind_level == 0 || ps.dec_nest > 0) {
917                 /* global variable or struct member in local variable */
918                 dec_ind = ps.decl_indent > 0 ? ps.decl_indent : i;
919                 tabs_to_var = (use_tabs ? ps.decl_indent > 0 : 0);
920             } else {
921                 /* local variable */
922                 dec_ind = ps.local_decl_indent > 0 ? ps.local_decl_indent : i;
923                 tabs_to_var = (use_tabs ? ps.local_decl_indent > 0 : 0);
924             }
925             goto copy_id;
926
927         case ident:             /* got an identifier or constant */
928             if (ps.in_decl) {   /* if we are in a declaration, we must indent
929                                  * identifier */
930                 if (is_procname == 0 || !procnames_start_line) {
931                     if (!ps.block_init) {
932                         if (troff && !ps.dumped_decl_indent) {
933                             if (ps.want_blank)
934                                 *e_code++ = ' ';
935                             ps.want_blank = false;
936                             sprintf(e_code, "\n.De %dp+\200p\n", dec_ind * 7);
937                             ps.dumped_decl_indent = 1;
938                             e_code += strlen(e_code);
939                         } else {
940                             int cur_dec_ind;
941                             int pos, startpos;
942
943                             /*
944                              * in order to get the tab math right for
945                              * indentations that are not multiples of 8 we
946                              * need to modify both startpos and dec_ind
947                              * (cur_dec_ind) here by eight minus the
948                              * remainder of the current starting column
949                              * divided by eight. This seems to be a
950                              * properly working fix
951                              */
952                             startpos = e_code - s_code;
953                             cur_dec_ind = dec_ind;
954                             pos = startpos;
955                             if ((ps.ind_level * ps.ind_size) % 8 != 0) {
956                                 pos += (ps.ind_level * ps.ind_size) % 8;
957                                 cur_dec_ind += (ps.ind_level * ps.ind_size) % 8;
958                             }
959
960                             if (tabs_to_var) {
961                                 while ((pos & ~7) + 8 <= cur_dec_ind) {
962                                     CHECK_SIZE_CODE;
963                                     *e_code++ = '\t';
964                                     pos = (pos & ~7) + 8;
965                                 }
966                             }
967                             while (pos < cur_dec_ind) {
968                                 CHECK_SIZE_CODE;
969                                 *e_code++ = ' ';
970                                 pos++;
971                             }
972                             if (ps.want_blank && e_code - s_code == startpos)
973                                 *e_code++ = ' ';
974                             ps.want_blank = false;
975                         }
976                     }
977                 } else {
978                     if (ps.want_blank)
979                         *e_code++ = ' ';
980                     ps.want_blank = false;
981                     if (dec_ind && s_code != e_code)
982                         dump_line();
983                     dec_ind = 0;
984                 }
985             }
986             else if (sp_sw && ps.p_l_follow == 0) {
987                 sp_sw = false;
988                 force_nl = true;
989                 ps.last_u_d = true;
990                 ps.in_stmt = false;
991                 parse(hd_type);
992             }
993     copy_id:
994             if (ps.want_blank)
995                 *e_code++ = ' ';
996             if (troff && ps.its_a_keyword) {
997                 e_code = chfont(&bodyf, &keywordf, e_code);
998                 for (t_ptr = token; *t_ptr; ++t_ptr) {
999                     CHECK_SIZE_CODE;
1000                     *e_code++ = keywordf.allcaps && islower(*t_ptr)
1001                         ? toupper(*t_ptr) : *t_ptr;
1002                 }
1003                 e_code = chfont(&keywordf, &bodyf, e_code);
1004             }
1005             else
1006                 for (t_ptr = token; *t_ptr; ++t_ptr) {
1007                     CHECK_SIZE_CODE;
1008                     *e_code++ = *t_ptr;
1009                 }
1010             ps.want_blank = true;
1011             break;
1012
1013         case period:            /* treat a period kind of like a binary
1014                                  * operation */
1015             *e_code++ = '.';    /* move the period into line */
1016             ps.want_blank = false;      /* dont put a blank after a period */
1017             break;
1018
1019         case comma:
1020             ps.want_blank = (s_code != e_code); /* only put blank after comma
1021                                                  * if comma does not start the
1022                                                  * line */
1023             if (ps.in_decl && is_procname == 0 && !ps.block_init)
1024                 while ((e_code - s_code) < (dec_ind - 1)) {
1025                     CHECK_SIZE_CODE;
1026                     *e_code++ = ' ';
1027                 }
1028
1029             *e_code++ = ',';
1030             if (ps.p_l_follow == 0) {
1031                 if (ps.block_init_level <= 0)
1032                     ps.block_init = 0;
1033                 if (break_comma && (!ps.leave_comma || compute_code_target() + (e_code - s_code) > max_col - 8))
1034                     force_nl = true;
1035             }
1036             break;
1037
1038         case preesc:            /* got the character '#' */
1039             if ((s_com != e_com) ||
1040                     (s_lab != e_lab) ||
1041                     (s_code != e_code))
1042                 dump_line();
1043             *e_lab++ = '#';     /* move whole line to 'label' buffer */
1044             {
1045                 int         in_comment = 0;
1046                 int         com_start = 0;
1047                 char        quote = 0;
1048                 int         com_end = 0;
1049
1050                 while (*buf_ptr == ' ' || *buf_ptr == '\t') {
1051                     buf_ptr++;
1052                     if (buf_ptr >= buf_end)
1053                         fill_buffer();
1054                 }
1055                 while (*buf_ptr != '\n' || (in_comment && !had_eof)) {
1056                     CHECK_SIZE_LAB;
1057                     *e_lab = *buf_ptr++;
1058                     if (buf_ptr >= buf_end)
1059                         fill_buffer();
1060                     switch (*e_lab++) {
1061                     case BACKSLASH:
1062                         if (troff)
1063                             *e_lab++ = BACKSLASH;
1064                         if (!in_comment) {
1065                             *e_lab++ = *buf_ptr++;
1066                             if (buf_ptr >= buf_end)
1067                                 fill_buffer();
1068                         }
1069                         break;
1070                     case '/':
1071                         if (*buf_ptr == '*' && !in_comment && !quote) {
1072                             in_comment = 1;
1073                             *e_lab++ = *buf_ptr++;
1074                             com_start = e_lab - s_lab - 2;
1075                         }
1076                         break;
1077                     case '"':
1078                         if (quote == '"')
1079                             quote = 0;
1080                         break;
1081                     case '\'':
1082                         if (quote == '\'')
1083                             quote = 0;
1084                         break;
1085                     case '*':
1086                         if (*buf_ptr == '/' && in_comment) {
1087                             in_comment = 0;
1088                             *e_lab++ = *buf_ptr++;
1089                             com_end = e_lab - s_lab;
1090                         }
1091                         break;
1092                     }
1093                 }
1094
1095                 while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
1096                     e_lab--;
1097                 if (e_lab - s_lab == com_end && bp_save == 0) { /* comment on
1098                                                                  * preprocessor line */
1099                     if (sc_end == 0)    /* if this is the first comment, we
1100                                          * must set up the buffer */
1101                         sc_end = &(save_com[0]);
1102                     else {
1103                         *sc_end++ = '\n';       /* add newline between
1104                                                  * comments */
1105                         *sc_end++ = ' ';
1106                         --line_no;
1107                     }
1108                     bcopy(s_lab + com_start, sc_end, com_end - com_start);
1109                     sc_end += com_end - com_start;
1110                     if (sc_end >= &save_com[sc_size])
1111                         abort();
1112                     e_lab = s_lab + com_start;
1113                     while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
1114                         e_lab--;
1115                     bp_save = buf_ptr;  /* save current input buffer */
1116                     be_save = buf_end;
1117                     buf_ptr = save_com; /* fix so that subsequent calls to
1118                                          * lexi will take tokens out of
1119                                          * save_com */
1120                     *sc_end++ = ' ';    /* add trailing blank, just in case */
1121                     buf_end = sc_end;
1122                     sc_end = 0;
1123                 }
1124                 *e_lab = '\0';  /* null terminate line */
1125                 ps.pcase = false;
1126             }
1127
1128             if (strncmp(s_lab, "#if", 3) == 0) {
1129                 if (blanklines_around_conditional_compilation) {
1130                     int c;
1131                     prefix_blankline_requested++;
1132                     while ((c = getc(input)) == '\n');
1133                     ungetc(c, input);
1134                 }
1135                 if ((size_t)ifdef_level < sizeof(state_stack)/sizeof(state_stack[0])) {
1136                     match_state[ifdef_level].tos = -1;
1137                     state_stack[ifdef_level++] = ps;
1138                 }
1139                 else
1140                     diag2(1, "#if stack overflow");
1141             }
1142             else if (strncmp(s_lab, "#else", 5) == 0)
1143                 if (ifdef_level <= 0)
1144                     diag2(1, "Unmatched #else");
1145                 else {
1146                     match_state[ifdef_level - 1] = ps;
1147                     ps = state_stack[ifdef_level - 1];
1148                 }
1149             else if (strncmp(s_lab, "#endif", 6) == 0) {
1150                 if (ifdef_level <= 0)
1151                     diag2(1, "Unmatched #endif");
1152                 else {
1153                     ifdef_level--;
1154
1155 #ifdef undef
1156                     /*
1157                      * This match needs to be more intelligent before the
1158                      * message is useful
1159                      */
1160                     if (match_state[ifdef_level].tos >= 0
1161                           && bcmp(&ps, &match_state[ifdef_level], sizeof ps))
1162                         diag2(0, "Syntactically inconsistent #ifdef alternatives");
1163 #endif
1164                 }
1165                 if (blanklines_around_conditional_compilation) {
1166                     postfix_blankline_requested++;
1167                     n_real_blanklines = 0;
1168                 }
1169             }
1170             break;              /* subsequent processing of the newline
1171                                  * character will cause the line to be printed */
1172
1173         case comment:           /* we have gotten a / followed by * this is a biggie */
1174             if (flushed_nl) {   /* we should force a broken line here */
1175                 flushed_nl = false;
1176                 dump_line();
1177                 ps.want_blank = false;  /* dont insert blank at line start */
1178                 force_nl = false;
1179             }
1180             pr_comment();
1181             break;
1182         }                       /* end of big switch stmt */
1183
1184         *e_code = '\0';         /* make sure code section is null terminated */
1185         if (type_code != comment && type_code != newline && type_code != preesc)
1186             ps.last_token = type_code;
1187     }                           /* end of main while (1) loop */
1188 }
1189
1190 /*
1191  * copy input file to backup file if in_name is /blah/blah/blah/file, then
1192  * backup file will be ".Bfile" then make the backup file the input and
1193  * original input file the output
1194  */
1195 static void
1196 bakcopy(void)
1197 {
1198     int         n,
1199                 bakchn;
1200     char        buff[8 * 1024];
1201     const char *p;
1202
1203     /* construct file name .Bfile */
1204     for (p = in_name; *p; p++); /* skip to end of string */
1205     while (p > in_name && *p != '/')    /* find last '/' */
1206         p--;
1207     if (*p == '/')
1208         p++;
1209     sprintf(bakfile, "%s.BAK", p);
1210
1211     /* copy in_name to backup file */
1212     bakchn = creat(bakfile, 0600);
1213     if (bakchn < 0)
1214         err(1, "%s", bakfile);
1215     while ((n = read(fileno(input), buff, sizeof buff)) != 0)
1216         if (write(bakchn, buff, n) != n)
1217             err(1, "%s", bakfile);
1218     if (n < 0)
1219         err(1, "%s", in_name);
1220     close(bakchn);
1221     fclose(input);
1222
1223     /* re-open backup file as the input file */
1224     input = fopen(bakfile, "r");
1225     if (input == 0)
1226         err(1, "%s", bakfile);
1227     /* now the original input file will be the output */
1228     output = fopen(in_name, "w");
1229     if (output == 0) {
1230         unlink(bakfile);
1231         err(1, "%s", in_name);
1232     }
1233 }