indent.c revision 1.174 1 /* $NetBSD: indent.c,v 1.174 2021/10/29 19:22:55 rillig Exp $ */
2
3 /*-
4 * SPDX-License-Identifier: BSD-4-Clause
5 *
6 * Copyright (c) 1985 Sun Microsystems, Inc.
7 * Copyright (c) 1976 Board of Trustees of the University of Illinois.
8 * Copyright (c) 1980, 1993
9 * The Regents of the University of California. All rights reserved.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
38 */
39
40 #if 0
41 static char sccsid[] = "@(#)indent.c 5.17 (Berkeley) 6/7/93";
42 #endif
43
44 #include <sys/cdefs.h>
45 #if defined(__NetBSD__)
46 __RCSID("$NetBSD: indent.c,v 1.174 2021/10/29 19:22:55 rillig Exp $");
47 #elif defined(__FreeBSD__)
48 __FBSDID("$FreeBSD: head/usr.bin/indent/indent.c 340138 2018-11-04 19:24:49Z oshogbo $");
49 #endif
50
51 #include <sys/param.h>
52 #if HAVE_CAPSICUM
53 #include <sys/capsicum.h>
54 #include <capsicum_helpers.h>
55 #endif
56 #include <ctype.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64
65 #include "indent.h"
66
67 struct options opt = {
68 .brace_same_line = true,
69 .comment_delimiter_on_blankline = true,
70 .cuddle_else = true,
71 .comment_column = 33,
72 .decl_indent = 16,
73 .else_if = true,
74 .function_brace_split = true,
75 .format_col1_comments = true,
76 .format_block_comments = true,
77 .indent_parameters = true,
78 .indent_size = 8,
79 .local_decl_indent = -1,
80 .lineup_to_parens = true,
81 .procnames_start_line = true,
82 .star_comment_cont = true,
83 .tabsize = 8,
84 .max_line_length = 78,
85 .use_tabs = true,
86 };
87
88 struct parser_state ps = {
89 .s_sym[0] = psym_stmt,
90 .prev_token = lsym_semicolon,
91 .prev_newline = true,
92 };
93
94 struct buffer lab;
95 struct buffer code;
96 struct buffer com;
97 struct buffer token;
98
99 struct buffer inp;
100
101 char sc_buf[sc_size];
102 char *save_com;
103 static char *sc_end; /* pointer into save_com buffer */
104
105 char *saved_inp_s;
106 char *saved_inp_e;
107
108 bool found_err;
109 int blank_lines_to_output;
110 bool blank_line_before;
111 bool blank_line_after;
112 bool break_comma;
113 float case_ind;
114 bool had_eof;
115 int line_no = 1;
116 bool inhibit_formatting;
117
118 static int ifdef_level;
119 static struct parser_state state_stack[5];
120
121 FILE *input;
122 FILE *output;
123
124 static const char *in_name = "Standard Input";
125 static const char *out_name = "Standard Output";
126 static const char *backup_suffix = ".BAK";
127 static char bakfile[MAXPATHLEN] = "";
128
129 #if HAVE_CAPSICUM
130 static void
131 init_capsicum(void)
132 {
133 cap_rights_t rights;
134
135 /* Restrict input/output descriptors and enter Capsicum sandbox. */
136 cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE);
137 if (caph_rights_limit(fileno(output), &rights) < 0)
138 err(EXIT_FAILURE, "unable to limit rights for %s", out_name);
139 cap_rights_init(&rights, CAP_FSTAT, CAP_READ);
140 if (caph_rights_limit(fileno(input), &rights) < 0)
141 err(EXIT_FAILURE, "unable to limit rights for %s", in_name);
142 if (caph_enter() < 0)
143 err(EXIT_FAILURE, "unable to enter capability mode");
144 }
145 #endif
146
147 void
148 diag(int level, const char *msg, ...)
149 {
150 va_list ap;
151
152 if (level != 0)
153 found_err = true;
154
155 va_start(ap, msg);
156 fprintf(stderr, "%s: %s:%d: ",
157 level == 0 ? "warning" : "error", in_name, line_no);
158 vfprintf(stderr, msg, ap);
159 fprintf(stderr, "\n");
160 va_end(ap);
161 }
162
163 static void
164 search_stmt_newline(bool *force_nl)
165 {
166 if (sc_end == NULL) {
167 save_com = sc_buf;
168 save_com[0] = save_com[1] = ' ';
169 sc_end = &save_com[2];
170 }
171 *sc_end++ = '\n';
172
173 line_no++;
174
175 /*
176 * We may have inherited a force_nl == true from the previous token (like
177 * a semicolon). But once we know that a newline has been scanned in this
178 * loop, force_nl should be false.
179 *
180 * However, the force_nl == true must be preserved if newline is never
181 * scanned in this loop, so this assignment cannot be done earlier.
182 */
183 *force_nl = false;
184 }
185
186 static void
187 search_stmt_comment(bool *comment_buffered)
188 {
189 if (sc_end == NULL) {
190 /*
191 * Copy everything from the start of the line, because
192 * process_comment() will use that to calculate original indentation
193 * of a boxed comment.
194 */
195 /*
196 * FIXME: This '4' needs an explanation. For example, in the snippet
197 * 'if(expr)/''*comment', the 'r)' of the code is not copied. If there
198 * is an additional line break before the ')', memcpy tries to copy
199 * (size_t)-1 bytes.
200 */
201 memcpy(sc_buf, inp.buf, (size_t)(inp.s - inp.buf) - 4);
202 save_com = sc_buf + (inp.s - inp.buf - 4);
203 save_com[0] = save_com[1] = ' ';
204 sc_end = &save_com[2];
205 }
206
207 *comment_buffered = true;
208 *sc_end++ = '/'; /* copy in start of comment */
209 *sc_end++ = '*';
210
211 for (;;) { /* loop until the end of the comment */
212 *sc_end++ = inbuf_next();
213 if (sc_end[-1] == '*' && *inp.s == '/')
214 break; /* we are at end of comment */
215 if (sc_end >= &save_com[sc_size]) { /* check for temp buffer
216 * overflow */
217 diag(1, "Internal buffer overflow - Move big comment from right after if, while, or whatever");
218 fflush(output);
219 exit(1);
220 }
221 }
222
223 *sc_end++ = '/'; /* add ending slash */
224 inbuf_skip(); /* get past / in buffer */
225 }
226
227 static bool
228 search_stmt_lbrace(void)
229 {
230 /*
231 * Put KNF-style lbraces before the buffered up tokens and jump out of
232 * this loop in order to avoid copying the token again.
233 */
234 if (sc_end != NULL && opt.brace_same_line) {
235 save_com[0] = '{';
236 /*
237 * Originally the lbrace may have been alone on its own line, but it
238 * will be moved into "the else's line", so if there was a newline
239 * resulting from the "{" before, it must be scanned now and ignored.
240 */
241 while (isspace((unsigned char)*inp.s)) {
242 inbuf_skip();
243 if (*inp.s == '\n')
244 break;
245 }
246 return true;
247 }
248 return false;
249 }
250
251 static bool
252 search_stmt_other(lexer_symbol lsym, bool *force_nl,
253 bool comment_buffered, bool last_else)
254 {
255 bool remove_newlines;
256
257 remove_newlines =
258 /* "} else" */
259 (lsym == lsym_else && code.e != code.s && code.e[-1] == '}')
260 /* "else if" */
261 || (lsym == lsym_if && last_else && opt.else_if);
262 if (remove_newlines)
263 *force_nl = false;
264
265 if (sc_end == NULL) { /* ignore buffering if comment wasn't saved
266 * up */
267 ps.search_stmt = false;
268 return false;
269 }
270
271 while (sc_end > save_com && isblank((unsigned char)sc_end[-1]))
272 sc_end--;
273
274 if (opt.swallow_optional_blanklines ||
275 (!comment_buffered && remove_newlines)) {
276 *force_nl = !remove_newlines;
277 while (sc_end > save_com && sc_end[-1] == '\n') {
278 sc_end--;
279 }
280 }
281
282 if (*force_nl) { /* if we should insert a nl here, put it into
283 * the buffer */
284 *force_nl = false;
285 --line_no; /* this will be re-increased when the newline
286 * is read from the buffer */
287 *sc_end++ = '\n';
288 *sc_end++ = ' ';
289 if (opt.verbose) /* warn if the line was not already broken */
290 diag(0, "Line broken");
291 }
292
293 /* XXX: buffer overflow? This is essentially a strcpy. */
294 for (const char *t_ptr = token.s; *t_ptr != '\0'; ++t_ptr)
295 *sc_end++ = *t_ptr;
296 return true;
297 }
298
299 static void
300 switch_buffer(void)
301 {
302 ps.search_stmt = false;
303 saved_inp_s = inp.s; /* save current input buffer */
304 saved_inp_e = inp.e;
305 inp.s = save_com; /* fix so that subsequent calls to lexi will
306 * take tokens out of save_com */
307 *sc_end++ = ' '; /* add trailing blank, just in case */
308 inp.e = sc_end;
309 sc_end = NULL;
310 debug_println("switched inp.s to save_com");
311 }
312
313 static void
314 search_stmt_lookahead(lexer_symbol *lsym)
315 {
316 if (*lsym == lsym_eof)
317 return;
318
319 /*
320 * The only intended purpose of calling lexi() below is to categorize the
321 * next token in order to decide whether to continue buffering forthcoming
322 * tokens. Once the buffering is over, lexi() will be called again
323 * elsewhere on all of the tokens - this time for normal processing.
324 *
325 * Calling it for this purpose is a bug, because lexi() also changes the
326 * parser state and discards leading whitespace, which is needed mostly
327 * for comment-related considerations.
328 *
329 * Work around the former problem by giving lexi() a copy of the current
330 * parser state and discard it if the call turned out to be just a
331 * lookahead.
332 *
333 * Work around the latter problem by copying all whitespace characters
334 * into the buffer so that the later lexi() call will read them.
335 */
336 if (sc_end != NULL) {
337 while (is_hspace(*inp.s)) {
338 *sc_end++ = *inp.s++;
339 if (sc_end >= &save_com[sc_size])
340 errx(1, "input too long");
341 }
342 if (inp.s >= inp.e)
343 inbuf_read_line();
344 }
345
346 struct parser_state backup_ps = ps;
347 *lsym = lexi();
348 if (*lsym == lsym_newline || *lsym == lsym_form_feed ||
349 *lsym == lsym_comment || ps.search_stmt) {
350 ps = backup_ps;
351 debug_println("rolled back parser state");
352 }
353 }
354
355 /*
356 * Move newlines and comments following an 'if (expr)', 'while (expr)',
357 * 'else', etc. up to the start of the following statement to a buffer. This
358 * allows proper handling of both kinds of brace placement (-br, -bl) and
359 * "cuddling else" (-ce).
360 */
361 static void
362 search_stmt(lexer_symbol *lsym, bool *force_nl,
363 bool *comment_buffered, bool *last_else)
364 {
365 while (ps.search_stmt) {
366 switch (*lsym) {
367 case lsym_newline:
368 search_stmt_newline(force_nl);
369 break;
370 case lsym_form_feed:
371 break;
372 case lsym_comment:
373 search_stmt_comment(comment_buffered);
374 break;
375 case lsym_lbrace:
376 if (search_stmt_lbrace())
377 goto switch_buffer;
378 /* FALLTHROUGH */
379 default: /* it is the start of a normal statement */
380 if (!search_stmt_other(*lsym, force_nl,
381 *comment_buffered, *last_else))
382 return;
383 switch_buffer:
384 switch_buffer();
385 }
386 search_stmt_lookahead(lsym);
387 }
388
389 *last_else = false;
390 }
391
392 static void
393 buf_init(struct buffer *buf)
394 {
395 size_t size = 200;
396 buf->buf = xmalloc(size);
397 buf->l = buf->buf + size - 5 /* safety margin */;
398 buf->s = buf->buf + 1; /* allow accessing buf->e[-1] */
399 buf->e = buf->s;
400 buf->buf[0] = ' ';
401 buf->buf[1] = '\0';
402 }
403
404 static size_t
405 buf_len(const struct buffer *buf)
406 {
407 return (size_t)(buf->e - buf->s);
408 }
409
410 void
411 buf_expand(struct buffer *buf, size_t add_size)
412 {
413 size_t new_size = (size_t)(buf->l - buf->s) + 400 + add_size;
414 size_t len = buf_len(buf);
415 buf->buf = xrealloc(buf->buf, new_size);
416 buf->l = buf->buf + new_size - 5;
417 buf->s = buf->buf + 1;
418 buf->e = buf->s + len;
419 /* At this point, the buffer may not be null-terminated anymore. */
420 }
421
422 static void
423 buf_reserve(struct buffer *buf, size_t n)
424 {
425 if (n >= (size_t)(buf->l - buf->e))
426 buf_expand(buf, n);
427 }
428
429 static void
430 buf_add_char(struct buffer *buf, char ch)
431 {
432 buf_reserve(buf, 1);
433 *buf->e++ = ch;
434 }
435
436 static void
437 buf_add_buf(struct buffer *buf, const struct buffer *add)
438 {
439 size_t len = buf_len(add);
440 buf_reserve(buf, len);
441 memcpy(buf->e, add->s, len);
442 buf->e += len;
443 }
444
445 static void
446 buf_terminate(struct buffer *buf)
447 {
448 buf_reserve(buf, 1);
449 *buf->e = '\0';
450 }
451
452 static void
453 buf_reset(struct buffer *buf)
454 {
455 buf->e = buf->s;
456 }
457
458 static void
459 main_init_globals(void)
460 {
461 inp.buf = xmalloc(10);
462 inp.l = inp.buf + 8;
463 inp.s = inp.buf;
464 inp.e = inp.buf;
465
466 buf_init(&token);
467
468 buf_init(&com);
469 buf_init(&lab);
470 buf_init(&code);
471
472 const char *suffix = getenv("SIMPLE_BACKUP_SUFFIX");
473 if (suffix != NULL)
474 backup_suffix = suffix;
475 }
476
477 /*
478 * Copy the input file to the backup file, then make the backup file the input
479 * and the original input file the output.
480 */
481 static void
482 bakcopy(void)
483 {
484 ssize_t n;
485 int bak_fd;
486 char buff[8 * 1024];
487
488 const char *last_slash = strrchr(in_name, '/');
489 snprintf(bakfile, sizeof(bakfile), "%s%s",
490 last_slash != NULL ? last_slash + 1 : in_name, backup_suffix);
491
492 /* copy in_name to backup file */
493 bak_fd = creat(bakfile, 0600);
494 if (bak_fd < 0)
495 err(1, "%s", bakfile);
496
497 while ((n = read(fileno(input), buff, sizeof(buff))) > 0)
498 if (write(bak_fd, buff, (size_t)n) != n)
499 err(1, "%s", bakfile);
500 if (n < 0)
501 err(1, "%s", in_name);
502
503 close(bak_fd);
504 (void)fclose(input);
505
506 /* re-open backup file as the input file */
507 input = fopen(bakfile, "r");
508 if (input == NULL)
509 err(1, "%s", bakfile);
510 /* now the original input file will be the output */
511 output = fopen(in_name, "w");
512 if (output == NULL) {
513 unlink(bakfile);
514 err(1, "%s", in_name);
515 }
516 }
517
518 static void
519 main_parse_command_line(int argc, char **argv)
520 {
521 int i;
522 const char *profile_name = NULL;
523
524 for (i = 1; i < argc; ++i)
525 if (strcmp(argv[i], "-npro") == 0)
526 break;
527 else if (argv[i][0] == '-' && argv[i][1] == 'P' && argv[i][2] != '\0')
528 profile_name = argv[i] + 2; /* non-empty -P (set profile) */
529 if (i >= argc)
530 load_profiles(profile_name);
531
532 for (i = 1; i < argc; ++i) {
533 if (argv[i][0] == '-') {
534 set_option(argv[i], "Command line");
535
536 } else if (input == NULL) {
537 in_name = argv[i];
538 input = fopen(in_name, "r");
539 if (input == NULL)
540 err(1, "%s", in_name);
541
542 } else if (output == NULL) {
543 out_name = argv[i];
544 if (strcmp(in_name, out_name) == 0)
545 errx(1, "input and output files must be different");
546 output = fopen(out_name, "w");
547 if (output == NULL)
548 err(1, "%s", out_name);
549
550 } else
551 errx(1, "too many arguments: %s", argv[i]);
552 }
553
554 if (input == NULL)
555 input = stdin;
556 if (output == NULL) {
557 if (input == stdin)
558 output = stdout;
559 else {
560 out_name = in_name;
561 bakcopy();
562 }
563 }
564
565 if (opt.comment_column <= 1)
566 opt.comment_column = 2; /* don't put normal comments before column 2 */
567 if (opt.block_comment_max_line_length <= 0)
568 opt.block_comment_max_line_length = opt.max_line_length;
569 if (opt.local_decl_indent < 0) /* if not specified by user, set this */
570 opt.local_decl_indent = opt.decl_indent;
571 if (opt.decl_comment_column <= 0) /* if not specified by user, set this */
572 opt.decl_comment_column = opt.ljust_decl
573 ? (opt.comment_column <= 10 ? 2 : opt.comment_column - 8)
574 : opt.comment_column;
575 if (opt.continuation_indent == 0)
576 opt.continuation_indent = opt.indent_size;
577 }
578
579 static void
580 main_prepare_parsing(void)
581 {
582 inbuf_read_line();
583
584 parse(psym_semicolon);
585
586 int ind = 0;
587 for (const char *p = inp.s;; p++) {
588 if (*p == ' ')
589 ind++;
590 else if (*p == '\t')
591 ind = next_tab(ind);
592 else
593 break;
594 }
595
596 if (ind >= opt.indent_size)
597 ps.ind_level = ps.ind_level_follow = ind / opt.indent_size;
598 }
599
600 static void
601 code_add_decl_indent(int cur_decl_ind, bool tabs_to_var)
602 {
603 int ind = (int)buf_len(&code);
604 char *orig_code_e = code.e;
605
606 /*
607 * get the tab math right for indentations that are not multiples of
608 * tabsize
609 */
610 if ((ps.ind_level * opt.indent_size) % opt.tabsize != 0) {
611 ind += (ps.ind_level * opt.indent_size) % opt.tabsize;
612 cur_decl_ind += (ps.ind_level * opt.indent_size) % opt.tabsize;
613 }
614
615 if (tabs_to_var) {
616 for (int next; (next = next_tab(ind)) <= cur_decl_ind; ind = next)
617 buf_add_char(&code, '\t');
618 }
619
620 for (; ind < cur_decl_ind; ind++)
621 buf_add_char(&code, ' ');
622
623 if (code.e == orig_code_e && ps.want_blank) {
624 *code.e++ = ' ';
625 ps.want_blank = false;
626 }
627 }
628
629 static void __attribute__((__noreturn__))
630 process_end_of_file(void)
631 {
632 if (lab.s != lab.e || code.s != code.e || com.s != com.e)
633 dump_line();
634
635 if (ps.tos > 1) /* check for balanced braces */
636 diag(1, "Stuff missing from end of file");
637
638 if (opt.verbose) {
639 printf("There were %d output lines and %d comments\n",
640 ps.stats.lines, ps.stats.comments);
641 printf("(Lines with comments)/(Lines with code): %6.3f\n",
642 (1.0 * ps.stats.comment_lines) / ps.stats.code_lines);
643 }
644
645 fflush(output);
646 exit(found_err ? EXIT_FAILURE : EXIT_SUCCESS);
647 }
648
649 static void
650 process_comment_in_code(lexer_symbol lsym, bool *force_nl)
651 {
652 if (*force_nl &&
653 lsym != lsym_semicolon &&
654 (lsym != lsym_lbrace || !opt.brace_same_line)) {
655
656 /* we should force a broken line here */
657 if (opt.verbose)
658 diag(0, "Line broken");
659 dump_line();
660 ps.want_blank = false; /* don't insert blank at line start */
661 *force_nl = false;
662 }
663
664 /* add an extra level of indentation; turned off again by a ';' or '}' */
665 ps.in_stmt = true;
666
667 if (com.s != com.e) { /* a comment embedded in a line */
668 buf_add_char(&code, ' ');
669 buf_add_buf(&code, &com);
670 buf_add_char(&code, ' ');
671 buf_terminate(&code);
672 buf_reset(&com);
673 ps.want_blank = false;
674 }
675 }
676
677 static void
678 process_form_feed(void)
679 {
680 dump_line_ff();
681 ps.want_blank = false;
682 }
683
684 static void
685 process_newline(void)
686 {
687 if (ps.prev_token == lsym_comma && ps.p_l_follow == 0 && !ps.block_init &&
688 !opt.break_after_comma && break_comma &&
689 com.s == com.e)
690 goto stay_in_line;
691
692 dump_line();
693 ps.want_blank = false;
694
695 stay_in_line:
696 ++line_no;
697 }
698
699 static bool
700 want_blank_before_lparen(void)
701 {
702 if (!ps.want_blank)
703 return false;
704 if (ps.prev_token == lsym_rparen_or_rbracket)
705 return false;
706 if (ps.prev_token != lsym_ident && ps.prev_token != lsym_funcname)
707 return true;
708 if (opt.proc_calls_space)
709 return true;
710 if (ps.prev_keyword == kw_sizeof)
711 return opt.blank_after_sizeof;
712 return ps.prev_keyword != kw_0 && ps.prev_keyword != kw_offsetof;
713 }
714
715 static void
716 process_lparen_or_lbracket(int decl_ind, bool tabs_to_var, bool spaced_expr)
717 {
718 if (++ps.p_l_follow == array_length(ps.paren_indents)) {
719 diag(0, "Reached internal limit of %zu unclosed parentheses",
720 array_length(ps.paren_indents));
721 ps.p_l_follow--;
722 }
723
724 if (token.s[0] == '(' && ps.in_decl
725 && !ps.block_init && !ps.decl_indent_done &&
726 ps.procname[0] == '\0' && ps.paren_level == 0) {
727 /* function pointer declarations */
728 code_add_decl_indent(decl_ind, tabs_to_var);
729 ps.decl_indent_done = true;
730 } else if (want_blank_before_lparen())
731 *code.e++ = ' ';
732 ps.want_blank = false;
733 *code.e++ = token.s[0];
734
735 ps.paren_indents[ps.p_l_follow - 1] =
736 (short)indentation_after_range(0, code.s, code.e);
737 debug_println("paren_indents[%d] is now %d",
738 ps.p_l_follow - 1, ps.paren_indents[ps.p_l_follow - 1]);
739
740 if (spaced_expr && ps.p_l_follow == 1 && opt.extra_expr_indent
741 && ps.paren_indents[0] < 2 * opt.indent_size) {
742 ps.paren_indents[0] = (short)(2 * opt.indent_size);
743 debug_println("paren_indents[0] is now %d", ps.paren_indents[0]);
744 }
745
746 if (ps.init_or_struct && *token.s == '(' && ps.tos <= 2) {
747 /*
748 * this is a kluge to make sure that declarations will be aligned
749 * right if proc decl has an explicit type on it, i.e. "int a(x) {..."
750 */
751 parse(psym_semicolon); /* I said this was a kluge... */
752 ps.init_or_struct = false;
753 }
754
755 /* parenthesized type following sizeof or offsetof is not a cast */
756 if (ps.prev_keyword == kw_offsetof || ps.prev_keyword == kw_sizeof)
757 ps.not_cast_mask |= 1 << ps.p_l_follow;
758 }
759
760 static void
761 process_rparen_or_rbracket(bool *spaced_expr, bool *force_nl, stmt_head hd)
762 {
763 if ((ps.cast_mask & (1 << ps.p_l_follow) & ~ps.not_cast_mask) != 0) {
764 ps.next_unary = true;
765 ps.cast_mask &= (1 << ps.p_l_follow) - 1;
766 ps.want_blank = opt.space_after_cast;
767 } else
768 ps.want_blank = true;
769 ps.not_cast_mask &= (1 << ps.p_l_follow) - 1;
770
771 if (ps.p_l_follow > 0)
772 ps.p_l_follow--;
773 else
774 diag(0, "Extra '%c'", *token.s);
775
776 if (code.e == code.s) /* if the paren starts the line */
777 ps.paren_level = ps.p_l_follow; /* then indent it */
778
779 *code.e++ = token.s[0];
780
781 if (*spaced_expr && ps.p_l_follow == 0) { /* check for end of 'if
782 * (...)', or some such */
783 *spaced_expr = false;
784 *force_nl = true; /* must force newline after if */
785 ps.next_unary = true;
786 ps.in_stmt = false; /* don't use stmt continuation indentation */
787
788 parse_stmt_head(hd);
789 }
790
791 /*
792 * This should ensure that constructs such as main(){...} and int[]{...}
793 * have their braces put in the right place.
794 */
795 ps.search_stmt = opt.brace_same_line;
796 }
797
798 static void
799 process_unary_op(int decl_ind, bool tabs_to_var)
800 {
801 if (!ps.decl_indent_done && ps.in_decl && !ps.block_init &&
802 ps.procname[0] == '\0' && ps.paren_level == 0) {
803 /* pointer declarations */
804 code_add_decl_indent(decl_ind - (int)buf_len(&token), tabs_to_var);
805 ps.decl_indent_done = true;
806 } else if (ps.want_blank)
807 *code.e++ = ' ';
808
809 buf_add_buf(&code, &token);
810 ps.want_blank = false;
811 }
812
813 static void
814 process_binary_op(void)
815 {
816 if (ps.want_blank)
817 buf_add_char(&code, ' ');
818 buf_add_buf(&code, &token);
819 ps.want_blank = true;
820 }
821
822 static void
823 process_postfix_op(void)
824 {
825 *code.e++ = token.s[0];
826 *code.e++ = token.s[1];
827 ps.want_blank = true;
828 }
829
830 static void
831 process_question(int *quest_level)
832 {
833 (*quest_level)++;
834 if (ps.want_blank)
835 *code.e++ = ' ';
836 *code.e++ = '?';
837 ps.want_blank = true;
838 }
839
840 static void
841 process_colon(int *quest_level, bool *force_nl, bool *seen_case)
842 {
843 if (*quest_level > 0) { /* part of a '?:' operator */
844 --*quest_level;
845 if (ps.want_blank)
846 *code.e++ = ' ';
847 *code.e++ = ':';
848 ps.want_blank = true;
849 return;
850 }
851
852 if (ps.init_or_struct) { /* bit-field */
853 *code.e++ = ':';
854 ps.want_blank = false;
855 return;
856 }
857
858 buf_add_buf(&lab, &code); /* 'case' or 'default' or named label */
859 buf_add_char(&lab, ':');
860 buf_terminate(&lab);
861 buf_reset(&code);
862
863 ps.in_stmt = false;
864 ps.is_case_label = *seen_case;
865 *force_nl = *seen_case;
866 *seen_case = false;
867 ps.want_blank = false;
868 }
869
870 static void
871 process_semicolon(bool *seen_case, int *quest_level, int decl_ind,
872 bool tabs_to_var, bool *spaced_expr, stmt_head hd, bool *force_nl)
873 {
874 if (ps.decl_nest == 0)
875 ps.init_or_struct = false;
876 *seen_case = false; /* these will only need resetting in an error */
877 *quest_level = 0;
878 if (ps.prev_token == lsym_rparen_or_rbracket)
879 ps.in_parameter_declaration = false;
880 ps.cast_mask = 0;
881 ps.not_cast_mask = 0;
882 ps.block_init = false;
883 ps.block_init_level = 0;
884 ps.just_saw_decl--;
885
886 if (ps.in_decl && code.s == code.e && !ps.block_init &&
887 !ps.decl_indent_done && ps.paren_level == 0) {
888 /* indent stray semicolons in declarations */
889 code_add_decl_indent(decl_ind - 1, tabs_to_var);
890 ps.decl_indent_done = true;
891 }
892
893 ps.in_decl = ps.decl_nest > 0; /* if we were in a first level
894 * structure declaration, we aren't
895 * anymore */
896
897 if ((!*spaced_expr || hd != hd_for) && ps.p_l_follow > 0) {
898
899 /*
900 * There were unbalanced parentheses in the statement. It is a bit
901 * complicated, because the semicolon might be in a for statement.
902 */
903 diag(1, "Unbalanced parentheses");
904 ps.p_l_follow = 0;
905 if (*spaced_expr) { /* 'if', 'while', etc. */
906 *spaced_expr = false;
907 parse_stmt_head(hd);
908 }
909 }
910 *code.e++ = ';';
911 ps.want_blank = true;
912 ps.in_stmt = ps.p_l_follow > 0;
913
914 if (!*spaced_expr) { /* if not if for (;;) */
915 parse(psym_semicolon); /* let parser know about end of stmt */
916 *force_nl = true; /* force newline after an end of stmt */
917 }
918 }
919
920 static void
921 process_lbrace(bool *force_nl, bool *spaced_expr, stmt_head hd,
922 int *di_stack, int di_stack_cap, int *decl_ind)
923 {
924 ps.in_stmt = false; /* don't indent the {} */
925
926 if (!ps.block_init)
927 *force_nl = true; /* force other stuff on same line as '{' onto
928 * new line */
929 else if (ps.block_init_level <= 0)
930 ps.block_init_level = 1;
931 else
932 ps.block_init_level++;
933
934 if (code.s != code.e && !ps.block_init) {
935 if (!opt.brace_same_line) {
936 dump_line();
937 ps.want_blank = false;
938 } else if (ps.in_parameter_declaration && !ps.init_or_struct) {
939 ps.ind_level_follow = 0;
940 if (opt.function_brace_split) { /* dump the line prior to the
941 * brace ... */
942 dump_line();
943 ps.want_blank = false;
944 } else /* add a space between the decl and brace */
945 ps.want_blank = true;
946 }
947 }
948
949 if (ps.in_parameter_declaration)
950 blank_line_before = false;
951
952 if (ps.p_l_follow > 0) {
953 diag(1, "Unbalanced parentheses");
954 ps.p_l_follow = 0;
955 if (*spaced_expr) { /* check for unclosed 'if', 'for', etc. */
956 *spaced_expr = false;
957 parse_stmt_head(hd);
958 ps.ind_level = ps.ind_level_follow;
959 }
960 }
961
962 if (code.s == code.e)
963 ps.ind_stmt = false; /* don't indent the '{' itself */
964 if (ps.in_decl && ps.init_or_struct) {
965 di_stack[ps.decl_nest] = *decl_ind;
966 if (++ps.decl_nest == di_stack_cap) {
967 diag(0, "Reached internal limit of %d struct levels",
968 di_stack_cap);
969 ps.decl_nest--;
970 }
971 } else {
972 ps.decl_on_line = false; /* we can't be in the middle of a
973 * declaration, so don't do special
974 * indentation of comments */
975 if (opt.blanklines_after_decl_at_top && ps.in_parameter_declaration)
976 blank_line_after = true;
977 ps.in_parameter_declaration = false;
978 ps.in_decl = false;
979 }
980
981 *decl_ind = 0;
982 parse(psym_lbrace);
983 if (ps.want_blank)
984 *code.e++ = ' ';
985 ps.want_blank = false;
986 *code.e++ = '{';
987 ps.just_saw_decl = 0;
988 }
989
990 static void
991 process_rbrace(bool *spaced_expr, int *decl_ind, const int *di_stack)
992 {
993 if (ps.s_sym[ps.tos] == psym_decl && !ps.block_init) {
994 /* semicolons can be omitted in declarations */
995 parse(psym_semicolon);
996 }
997
998 if (ps.p_l_follow > 0) { /* check for unclosed if, for, else. */
999 diag(1, "Unbalanced parentheses");
1000 ps.p_l_follow = 0;
1001 *spaced_expr = false;
1002 }
1003
1004 ps.just_saw_decl = 0;
1005 ps.block_init_level--;
1006
1007 if (code.s != code.e && !ps.block_init) { /* '}' must be first on line */
1008 if (opt.verbose)
1009 diag(0, "Line broken");
1010 dump_line();
1011 }
1012
1013 *code.e++ = '}';
1014 ps.want_blank = true;
1015 ps.in_stmt = ps.ind_stmt = false;
1016
1017 if (ps.decl_nest > 0) { /* we are in multi-level structure declaration */
1018 *decl_ind = di_stack[--ps.decl_nest];
1019 if (ps.decl_nest == 0 && !ps.in_parameter_declaration) {
1020 ps.just_saw_decl = 2;
1021 *decl_ind = ps.ind_level == 0
1022 ? opt.decl_indent : opt.local_decl_indent;
1023 }
1024 ps.in_decl = true;
1025 }
1026
1027 blank_line_before = false;
1028 parse(psym_rbrace);
1029 ps.search_stmt = opt.cuddle_else
1030 && ps.s_sym[ps.tos] == psym_if_expr_stmt
1031 && ps.s_ind_level[ps.tos] >= ps.ind_level;
1032
1033 if (ps.tos <= 1 && opt.blanklines_after_procs && ps.decl_nest <= 0)
1034 blank_line_after = true;
1035 }
1036
1037 static void
1038 process_keyword_do(bool *force_nl, bool *last_else)
1039 {
1040 ps.in_stmt = false;
1041
1042 if (code.e != code.s) { /* make sure this starts a line */
1043 if (opt.verbose)
1044 diag(0, "Line broken");
1045 dump_line();
1046 ps.want_blank = false;
1047 }
1048
1049 *force_nl = true; /* following stuff must go onto new line */
1050 *last_else = false;
1051 parse(psym_do);
1052 }
1053
1054 static void
1055 process_keyword_else(bool *force_nl, bool *last_else)
1056 {
1057 ps.in_stmt = false;
1058
1059 if (code.e != code.s && (!opt.cuddle_else || code.e[-1] != '}')) {
1060 if (opt.verbose)
1061 diag(0, "Line broken");
1062 dump_line(); /* make sure this starts a line */
1063 ps.want_blank = false;
1064 }
1065
1066 *force_nl = true; /* following stuff must go onto new line */
1067 *last_else = true;
1068 parse(psym_else);
1069 }
1070
1071 static void
1072 process_type(int *decl_ind, bool *tabs_to_var)
1073 {
1074 parse(psym_decl); /* let the parser worry about indentation */
1075
1076 if (ps.prev_token == lsym_rparen_or_rbracket && ps.tos <= 1) {
1077 if (code.s != code.e) {
1078 dump_line();
1079 ps.want_blank = false;
1080 }
1081 }
1082
1083 if (ps.in_parameter_declaration && opt.indent_parameters &&
1084 ps.decl_nest == 0) {
1085 ps.ind_level = ps.ind_level_follow = 1;
1086 ps.ind_stmt = false;
1087 }
1088
1089 ps.init_or_struct = /* maybe */ true;
1090 ps.in_decl = ps.decl_on_line = ps.prev_token != lsym_typedef;
1091 if (ps.decl_nest <= 0)
1092 ps.just_saw_decl = 2;
1093
1094 blank_line_before = false;
1095
1096 int len = (int)buf_len(&token) + 1;
1097 int ind = ps.ind_level == 0 || ps.decl_nest > 0
1098 ? opt.decl_indent /* global variable or local member */
1099 : opt.local_decl_indent; /* local variable */
1100 *decl_ind = ind > 0 ? ind : len;
1101 *tabs_to_var = opt.use_tabs && ind > 0;
1102 }
1103
1104 static void
1105 process_ident(lexer_symbol lsym, int decl_ind, bool tabs_to_var,
1106 bool *spaced_expr, bool *force_nl, stmt_head hd)
1107 {
1108 if (ps.in_decl) {
1109 if (lsym == lsym_funcname) {
1110 ps.in_decl = false;
1111 if (opt.procnames_start_line && code.s != code.e) {
1112 *code.e = '\0';
1113 dump_line();
1114 } else if (ps.want_blank) {
1115 *code.e++ = ' ';
1116 }
1117 ps.want_blank = false;
1118
1119 } else if (!ps.block_init && !ps.decl_indent_done &&
1120 ps.paren_level == 0) {
1121 code_add_decl_indent(decl_ind, tabs_to_var);
1122 ps.decl_indent_done = true;
1123 ps.want_blank = false;
1124 }
1125
1126 } else if (*spaced_expr && ps.p_l_follow == 0) {
1127 *spaced_expr = false;
1128 *force_nl = true;
1129 ps.next_unary = true;
1130 ps.in_stmt = false;
1131 parse_stmt_head(hd);
1132 }
1133 }
1134
1135 static void
1136 copy_token(void)
1137 {
1138 if (ps.want_blank)
1139 buf_add_char(&code, ' ');
1140 buf_add_buf(&code, &token);
1141 }
1142
1143 static void
1144 process_string_prefix(void)
1145 {
1146 copy_token();
1147 ps.want_blank = false;
1148 }
1149
1150 static void
1151 process_period(void)
1152 {
1153 if (code.e[-1] == ',')
1154 *code.e++ = ' ';
1155 *code.e++ = '.';
1156 ps.want_blank = false;
1157 }
1158
1159 static void
1160 process_comma(int decl_ind, bool tabs_to_var, bool *force_nl)
1161 {
1162 ps.want_blank = code.s != code.e; /* only put blank after comma if comma
1163 * does not start the line */
1164
1165 if (ps.in_decl && ps.procname[0] == '\0' && !ps.block_init &&
1166 !ps.decl_indent_done && ps.paren_level == 0) {
1167 /* indent leading commas and not the actual identifiers */
1168 code_add_decl_indent(decl_ind - 1, tabs_to_var);
1169 ps.decl_indent_done = true;
1170 }
1171
1172 *code.e++ = ',';
1173
1174 if (ps.p_l_follow == 0) {
1175 if (ps.block_init_level <= 0)
1176 ps.block_init = false;
1177 if (break_comma && (opt.break_after_comma ||
1178 indentation_after_range(compute_code_indent(), code.s, code.e)
1179 >= opt.max_line_length - opt.tabsize))
1180 *force_nl = true;
1181 }
1182 }
1183
1184 /* move the whole line to the 'label' buffer */
1185 static void
1186 read_preprocessing_line(void)
1187 {
1188 enum {
1189 PLAIN, STR, CHR, COMM
1190 } state;
1191
1192 buf_add_char(&lab, '#');
1193
1194 state = PLAIN;
1195 int com_start = 0, com_end = 0;
1196
1197 while (is_hspace(*inp.s))
1198 inbuf_skip();
1199
1200 while (*inp.s != '\n' || (state == COMM && !had_eof)) {
1201 buf_reserve(&lab, 2);
1202 *lab.e++ = inbuf_next();
1203 switch (lab.e[-1]) {
1204 case '\\':
1205 if (state != COMM)
1206 *lab.e++ = inbuf_next();
1207 break;
1208 case '/':
1209 if (*inp.s == '*' && state == PLAIN) {
1210 state = COMM;
1211 *lab.e++ = *inp.s++;
1212 com_start = (int)buf_len(&lab) - 2;
1213 }
1214 break;
1215 case '"':
1216 if (state == STR)
1217 state = PLAIN;
1218 else if (state == PLAIN)
1219 state = STR;
1220 break;
1221 case '\'':
1222 if (state == CHR)
1223 state = PLAIN;
1224 else if (state == PLAIN)
1225 state = CHR;
1226 break;
1227 case '*':
1228 if (*inp.s == '/' && state == COMM) {
1229 state = PLAIN;
1230 *lab.e++ = *inp.s++;
1231 com_end = (int)buf_len(&lab);
1232 }
1233 break;
1234 }
1235 }
1236
1237 while (lab.e > lab.s && is_hspace(lab.e[-1]))
1238 lab.e--;
1239 if (lab.e - lab.s == com_end && saved_inp_s == NULL) {
1240 /* comment on preprocessor line */
1241 if (sc_end == NULL) { /* if this is the first comment, we must set
1242 * up the buffer */
1243 save_com = sc_buf;
1244 sc_end = save_com;
1245 } else {
1246 *sc_end++ = '\n'; /* add newline between comments */
1247 *sc_end++ = ' ';
1248 --line_no;
1249 }
1250 if (sc_end - save_com + com_end - com_start > sc_size)
1251 errx(1, "input too long");
1252 memmove(sc_end, lab.s + com_start, (size_t)(com_end - com_start));
1253 sc_end += com_end - com_start;
1254 lab.e = lab.s + com_start;
1255 while (lab.e > lab.s && is_hspace(lab.e[-1]))
1256 lab.e--;
1257 saved_inp_s = inp.s; /* save current input buffer */
1258 saved_inp_e = inp.e;
1259 inp.s = save_com; /* fix so that subsequent calls to lexi will
1260 * take tokens out of save_com */
1261 *sc_end++ = ' '; /* add trailing blank, just in case */
1262 inp.e = sc_end;
1263 sc_end = NULL;
1264 debug_println("switched inp.s to save_com");
1265 }
1266 buf_terminate(&lab);
1267 }
1268
1269 static void
1270 process_preprocessing(void)
1271 {
1272 if (com.s != com.e || lab.s != lab.e || code.s != code.e)
1273 dump_line();
1274
1275 read_preprocessing_line();
1276
1277 ps.is_case_label = false;
1278
1279 if (strncmp(lab.s, "#if", 3) == 0) { /* also ifdef, ifndef */
1280 if ((size_t)ifdef_level < array_length(state_stack))
1281 state_stack[ifdef_level++] = ps;
1282 else
1283 diag(1, "#if stack overflow");
1284
1285 } else if (strncmp(lab.s, "#el", 3) == 0) { /* else, elif */
1286 if (ifdef_level <= 0)
1287 diag(1, lab.s[3] == 'i' ? "Unmatched #elif" : "Unmatched #else");
1288 else
1289 ps = state_stack[ifdef_level - 1];
1290
1291 } else if (strncmp(lab.s, "#endif", 6) == 0) {
1292 if (ifdef_level <= 0)
1293 diag(1, "Unmatched #endif");
1294 else
1295 ifdef_level--;
1296
1297 } else {
1298 if (strncmp(lab.s + 1, "pragma", 6) != 0 &&
1299 strncmp(lab.s + 1, "error", 5) != 0 &&
1300 strncmp(lab.s + 1, "line", 4) != 0 &&
1301 strncmp(lab.s + 1, "undef", 5) != 0 &&
1302 strncmp(lab.s + 1, "define", 6) != 0 &&
1303 strncmp(lab.s + 1, "include", 7) != 0) {
1304 diag(1, "Unrecognized cpp directive");
1305 return;
1306 }
1307 }
1308
1309 if (opt.blanklines_around_conditional_compilation) {
1310 blank_line_after = true;
1311 blank_lines_to_output = 0;
1312 } else {
1313 blank_line_after = false;
1314 blank_line_before = false;
1315 }
1316
1317 /*
1318 * subsequent processing of the newline character will cause the line to
1319 * be printed
1320 */
1321 }
1322
1323 static void __attribute__((__noreturn__))
1324 main_loop(void)
1325 {
1326 bool force_nl = false; /* when true, code must be broken */
1327 bool last_else = false; /* true iff last keyword was an else */
1328 int decl_ind = 0; /* current indentation for declarations */
1329 int di_stack[20]; /* a stack of structure indentation levels */
1330 bool tabs_to_var = false; /* true if using tabs to indent to var name */
1331 bool spaced_expr = false; /* whether we are in the expression of
1332 * if(...), while(...), etc. */
1333 stmt_head hd = hd_0; /* the type of statement for 'if (...)', 'for
1334 * (...)', etc */
1335 int quest_level = 0; /* when this is positive, we have seen a '?'
1336 * without the matching ':' in a '?:'
1337 * expression */
1338 bool seen_case = false; /* set to true when we see a 'case', so we
1339 * know what to do with the following colon */
1340
1341 di_stack[ps.decl_nest = 0] = 0;
1342
1343 for (;;) { /* this is the main loop. it will go until we
1344 * reach eof */
1345 bool comment_buffered = false;
1346
1347 lexer_symbol lsym = lexi(); /* Read the next token. The actual
1348 * characters read are stored in
1349 * "token". */
1350
1351 search_stmt(&lsym, &force_nl, &comment_buffered, &last_else);
1352
1353 if (lsym == lsym_eof) {
1354 process_end_of_file();
1355 /* NOTREACHED */
1356 }
1357
1358 if (lsym == lsym_newline || lsym == lsym_form_feed ||
1359 lsym == lsym_preprocessing)
1360 force_nl = false;
1361 else if (lsym != lsym_comment)
1362 process_comment_in_code(lsym, &force_nl);
1363
1364 buf_reserve(&code, 3); /* space for 2 characters plus '\0' */
1365
1366 switch (lsym) {
1367
1368 case lsym_form_feed:
1369 process_form_feed();
1370 break;
1371
1372 case lsym_newline:
1373 process_newline();
1374 break;
1375
1376 case lsym_lparen_or_lbracket:
1377 process_lparen_or_lbracket(decl_ind, tabs_to_var, spaced_expr);
1378 break;
1379
1380 case lsym_rparen_or_rbracket:
1381 process_rparen_or_rbracket(&spaced_expr, &force_nl, hd);
1382 break;
1383
1384 case lsym_unary_op:
1385 process_unary_op(decl_ind, tabs_to_var);
1386 break;
1387
1388 case lsym_binary_op:
1389 process_binary_op();
1390 break;
1391
1392 case lsym_postfix_op:
1393 process_postfix_op();
1394 break;
1395
1396 case lsym_question:
1397 process_question(&quest_level);
1398 break;
1399
1400 case lsym_case_label:
1401 seen_case = true;
1402 goto copy_token;
1403
1404 case lsym_colon:
1405 process_colon(&quest_level, &force_nl, &seen_case);
1406 break;
1407
1408 case lsym_semicolon:
1409 process_semicolon(&seen_case, &quest_level, decl_ind, tabs_to_var,
1410 &spaced_expr, hd, &force_nl);
1411 break;
1412
1413 case lsym_lbrace:
1414 process_lbrace(&force_nl, &spaced_expr, hd, di_stack,
1415 (int)array_length(di_stack), &decl_ind);
1416 break;
1417
1418 case lsym_rbrace:
1419 process_rbrace(&spaced_expr, &decl_ind, di_stack);
1420 break;
1421
1422 case lsym_switch:
1423 spaced_expr = true; /* the interesting stuff is done after the
1424 * expressions are scanned */
1425 hd = hd_switch; /* remember the type of header for later use
1426 * by the parser */
1427 goto copy_token;
1428
1429 case lsym_for:
1430 spaced_expr = true;
1431 hd = hd_for;
1432 goto copy_token;
1433
1434 case lsym_if:
1435 spaced_expr = true;
1436 hd = hd_if;
1437 goto copy_token;
1438
1439 case lsym_while:
1440 spaced_expr = true;
1441 hd = hd_while;
1442 goto copy_token;
1443
1444 case lsym_do:
1445 process_keyword_do(&force_nl, &last_else);
1446 goto copy_token;
1447
1448 case lsym_else:
1449 process_keyword_else(&force_nl, &last_else);
1450 goto copy_token;
1451
1452 case lsym_typedef:
1453 case lsym_storage_class:
1454 blank_line_before = false;
1455 goto copy_token;
1456
1457 case lsym_tag:
1458 if (ps.p_l_follow > 0)
1459 goto copy_token;
1460 /* FALLTHROUGH */
1461 case lsym_type:
1462 process_type(&decl_ind, &tabs_to_var);
1463 goto copy_token;
1464
1465 case lsym_funcname:
1466 case lsym_ident:
1467 process_ident(lsym, decl_ind, tabs_to_var, &spaced_expr,
1468 &force_nl, hd);
1469 copy_token:
1470 copy_token();
1471 if (lsym != lsym_funcname)
1472 ps.want_blank = true;
1473 break;
1474
1475 case lsym_string_prefix:
1476 process_string_prefix();
1477 break;
1478
1479 case lsym_period:
1480 process_period();
1481 break;
1482
1483 case lsym_comma:
1484 process_comma(decl_ind, tabs_to_var, &force_nl);
1485 break;
1486
1487 case lsym_preprocessing:
1488 process_preprocessing();
1489 break;
1490
1491 case lsym_comment:
1492 process_comment();
1493 break;
1494
1495 default:
1496 break;
1497 }
1498
1499 *code.e = '\0';
1500 if (lsym != lsym_comment && lsym != lsym_newline &&
1501 lsym != lsym_preprocessing)
1502 ps.prev_token = lsym;
1503 }
1504 }
1505
1506 int
1507 main(int argc, char **argv)
1508 {
1509 main_init_globals();
1510 main_parse_command_line(argc, argv);
1511 #if HAVE_CAPSICUM
1512 init_capsicum();
1513 #endif
1514 main_prepare_parsing();
1515 main_loop();
1516 }
1517
1518 #ifdef debug
1519 void
1520 debug_printf(const char *fmt, ...)
1521 {
1522 FILE *f = output == stdout ? stderr : stdout;
1523 va_list ap;
1524
1525 va_start(ap, fmt);
1526 vfprintf(f, fmt, ap);
1527 va_end(ap);
1528 }
1529
1530 void
1531 debug_println(const char *fmt, ...)
1532 {
1533 FILE *f = output == stdout ? stderr : stdout;
1534 va_list ap;
1535
1536 va_start(ap, fmt);
1537 vfprintf(f, fmt, ap);
1538 va_end(ap);
1539 fprintf(f, "\n");
1540 }
1541
1542 void
1543 debug_vis_range(const char *prefix, const char *s, const char *e,
1544 const char *suffix)
1545 {
1546 debug_printf("%s", prefix);
1547 for (const char *p = s; p < e; p++) {
1548 if (*p == '\\' || *p == '"')
1549 debug_printf("\\%c", *p);
1550 else if (isprint((unsigned char)*p))
1551 debug_printf("%c", *p);
1552 else if (*p == '\n')
1553 debug_printf("\\n");
1554 else if (*p == '\t')
1555 debug_printf("\\t");
1556 else
1557 debug_printf("\\x%02x", (unsigned char)*p);
1558 }
1559 debug_printf("%s", suffix);
1560 }
1561 #endif
1562
1563 static void *
1564 nonnull(void *p)
1565 {
1566 if (p == NULL)
1567 err(EXIT_FAILURE, NULL);
1568 return p;
1569 }
1570
1571 void *
1572 xmalloc(size_t size)
1573 {
1574 return nonnull(malloc(size));
1575 }
1576
1577 void *
1578 xrealloc(void *p, size_t new_size)
1579 {
1580 return nonnull(realloc(p, new_size));
1581 }
1582
1583 char *
1584 xstrdup(const char *s)
1585 {
1586 return nonnull(strdup(s));
1587 }
1588