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