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