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