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