indent.c revision 1.148 1 /* $NetBSD: indent.c,v 1.148 2021/10/24 17:19:48 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.148 2021/10/24 17:19:48 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
90 struct buffer lab;
91 struct buffer code;
92 struct buffer com;
93 struct buffer token;
94
95 struct buffer inp;
96
97 char sc_buf[sc_size];
98 char *save_com;
99 static char *sc_end; /* pointer into save_com buffer */
100
101 char *saved_inp_s;
102 char *saved_inp_e;
103
104 bool found_err;
105 int blank_lines_to_output;
106 bool blank_line_before;
107 bool blank_line_after;
108 bool break_comma;
109 float case_ind;
110 bool had_eof;
111 int line_no;
112 bool inhibit_formatting;
113
114 static int ifdef_level;
115 static struct parser_state state_stack[5];
116
117 FILE *input;
118 FILE *output;
119
120 static const char *in_name = "Standard Input";
121 static const char *out_name = "Standard Output";
122 static const char *backup_suffix = ".BAK";
123 static char bakfile[MAXPATHLEN] = "";
124
125 #if HAVE_CAPSICUM
126 static void
127 init_capsicum(void)
128 {
129 cap_rights_t rights;
130
131 /* Restrict input/output descriptors and enter Capsicum sandbox. */
132 cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE);
133 if (caph_rights_limit(fileno(output), &rights) < 0)
134 err(EXIT_FAILURE, "unable to limit rights for %s", out_name);
135 cap_rights_init(&rights, CAP_FSTAT, CAP_READ);
136 if (caph_rights_limit(fileno(input), &rights) < 0)
137 err(EXIT_FAILURE, "unable to limit rights for %s", in_name);
138 if (caph_enter() < 0)
139 err(EXIT_FAILURE, "unable to enter capability mode");
140 }
141 #endif
142
143 void
144 diag(int level, const char *msg, ...)
145 {
146 va_list ap;
147
148 if (level != 0)
149 found_err = true;
150
151 va_start(ap, msg);
152 fprintf(stderr, "%s: %s:%d: ",
153 level == 0 ? "warning" : "error", in_name, line_no);
154 vfprintf(stderr, msg, ap);
155 fprintf(stderr, "\n");
156 va_end(ap);
157 }
158
159 static void
160 search_brace_newline(bool *force_nl)
161 {
162 if (sc_end == NULL) {
163 save_com = sc_buf;
164 save_com[0] = save_com[1] = ' ';
165 sc_end = &save_com[2];
166 }
167 *sc_end++ = '\n';
168
169 line_no++;
170
171 /*
172 * We may have inherited a force_nl == true from the previous token (like
173 * a semicolon). But once we know that a newline has been scanned in this
174 * loop, force_nl should be false.
175 *
176 * However, the force_nl == true must be preserved if newline is never
177 * scanned in this loop, so this assignment cannot be done earlier.
178 */
179 *force_nl = false;
180 }
181
182 static void
183 search_brace_comment(bool *comment_buffered)
184 {
185 if (sc_end == NULL) {
186 /*
187 * Copy everything from the start of the line, because
188 * process_comment() will use that to calculate original indentation
189 * of a boxed comment.
190 */
191 memcpy(sc_buf, inp.buf, (size_t)(inp.s - inp.buf) - 4);
192 save_com = sc_buf + (inp.s - inp.buf - 4);
193 save_com[0] = save_com[1] = ' ';
194 sc_end = &save_com[2];
195 }
196
197 *comment_buffered = true;
198 *sc_end++ = '/'; /* copy in start of comment */
199 *sc_end++ = '*';
200
201 for (;;) { /* loop until the end of the comment */
202 *sc_end++ = inbuf_next();
203 if (sc_end[-1] == '*' && *inp.s == '/')
204 break; /* we are at end of comment */
205 if (sc_end >= &save_com[sc_size]) { /* check for temp buffer
206 * overflow */
207 diag(1, "Internal buffer overflow - Move big comment from right after if, while, or whatever");
208 fflush(output);
209 exit(1);
210 }
211 }
212
213 *sc_end++ = '/'; /* add ending slash */
214 inbuf_skip(); /* get past / in buffer */
215 }
216
217 static bool
218 search_brace_lbrace(void)
219 {
220 /*
221 * Put KNF-style lbraces before the buffered up tokens and jump out of
222 * this loop in order to avoid copying the token again.
223 */
224 if (sc_end != NULL && opt.brace_same_line) {
225 save_com[0] = '{';
226 /*
227 * Originally the lbrace may have been alone on its own line, but it
228 * will be moved into "the else's line", so if there was a newline
229 * resulting from the "{" before, it must be scanned now and ignored.
230 */
231 while (isspace((unsigned char)*inp.s)) {
232 inbuf_skip();
233 if (*inp.s == '\n')
234 break;
235 }
236 return true;
237 }
238 return false;
239 }
240
241 static bool
242 search_brace_other(token_type ttype, bool *force_nl,
243 bool comment_buffered, bool last_else)
244 {
245 bool remove_newlines;
246
247 remove_newlines =
248 /* "} else" */
249 (ttype == keyword_do_else && *token.s == 'e' &&
250 code.e != code.s && code.e[-1] == '}')
251 /* "else if" */
252 || (ttype == keyword_for_if_while &&
253 *token.s == 'i' && last_else && opt.else_if);
254 if (remove_newlines)
255 *force_nl = false;
256
257 if (sc_end == NULL) { /* ignore buffering if comment wasn't saved
258 * up */
259 ps.search_brace = false;
260 return false;
261 }
262
263 while (sc_end > save_com && isblank((unsigned char)sc_end[-1]))
264 sc_end--;
265
266 if (opt.swallow_optional_blanklines ||
267 (!comment_buffered && remove_newlines)) {
268 *force_nl = !remove_newlines;
269 while (sc_end > save_com && sc_end[-1] == '\n') {
270 sc_end--;
271 }
272 }
273
274 if (*force_nl) { /* if we should insert a nl here, put it into
275 * the buffer */
276 *force_nl = false;
277 --line_no; /* this will be re-increased when the newline
278 * is read from the buffer */
279 *sc_end++ = '\n';
280 *sc_end++ = ' ';
281 if (opt.verbose) /* warn if the line was not already broken */
282 diag(0, "Line broken");
283 }
284
285 /* XXX: buffer overflow? This is essentially a strcpy. */
286 for (const char *t_ptr = token.s; *t_ptr != '\0'; ++t_ptr)
287 *sc_end++ = *t_ptr;
288 return true;
289 }
290
291 static void
292 switch_buffer(void)
293 {
294 ps.search_brace = false; /* stop looking for start of stmt */
295 saved_inp_s = inp.s; /* save current input buffer */
296 saved_inp_e = inp.e;
297 inp.s = save_com; /* fix so that subsequent calls to lexi will
298 * take tokens out of save_com */
299 *sc_end++ = ' '; /* add trailing blank, just in case */
300 inp.e = sc_end;
301 sc_end = NULL;
302 debug_println("switched inp.s to save_com");
303 }
304
305 static void
306 search_brace_lookahead(token_type *ttype)
307 {
308 if (*ttype == end_of_file)
309 return;
310
311 /*
312 * The only intended purpose of calling lexi() below is to categorize
313 * the next token in order to decide whether to continue buffering
314 * forthcoming tokens. Once the buffering is over, lexi() will be
315 * called again elsewhere on all of the tokens - this time for normal
316 * processing.
317 *
318 * Calling it for this purpose is a bug, because lexi() also changes
319 * the parser state and discards leading whitespace, which is needed
320 * mostly for comment-related considerations.
321 *
322 * Work around the former problem by giving lexi() a copy of the
323 * current parser state and discard it if the call turned out to be
324 * just a lookahead.
325 *
326 * Work around the latter problem by copying all whitespace characters
327 * into the buffer so that the later lexi() call will read them.
328 */
329 if (sc_end != NULL) {
330 while (is_hspace(*inp.s)) {
331 *sc_end++ = *inp.s++;
332 if (sc_end >= &save_com[sc_size])
333 errx(1, "input too long");
334 }
335 if (inp.s >= inp.e)
336 inbuf_read_line();
337 }
338
339 struct parser_state transient_state;
340 transient_state = ps;
341 *ttype = lexi(&transient_state); /* read another token */
342 if (*ttype != newline && *ttype != form_feed &&
343 *ttype != comment && !transient_state.search_brace) {
344 ps = transient_state;
345 }
346 }
347
348 static void
349 search_brace(token_type *ttype, bool *force_nl,
350 bool *comment_buffered, bool *last_else)
351 {
352 while (ps.search_brace) {
353 switch (*ttype) {
354 case newline:
355 search_brace_newline(force_nl);
356 break;
357 case form_feed:
358 break;
359 case comment:
360 search_brace_comment(comment_buffered);
361 break;
362 case lbrace:
363 if (search_brace_lbrace())
364 goto switch_buffer;
365 /* FALLTHROUGH */
366 default: /* it is the start of a normal statement */
367 if (!search_brace_other(*ttype, force_nl,
368 *comment_buffered, *last_else))
369 return;
370 switch_buffer:
371 switch_buffer();
372 }
373 search_brace_lookahead(ttype);
374 }
375
376 *last_else = false;
377 }
378
379 static void
380 buf_init(struct buffer *buf)
381 {
382 size_t size = 200;
383 buf->buf = xmalloc(size);
384 buf->buf[0] = ' '; /* allow accessing buf->e[-1] */
385 buf->buf[1] = '\0';
386 buf->s = buf->buf + 1;
387 buf->e = buf->s;
388 buf->l = buf->buf + size - 5; /* safety margin */
389 }
390
391 static size_t
392 buf_len(const struct buffer *buf)
393 {
394 return (size_t)(buf->e - buf->s);
395 }
396
397 void
398 buf_expand(struct buffer *buf, size_t desired_size)
399 {
400 size_t nsize = (size_t)(buf->l - buf->s) + 400 + desired_size;
401 size_t len = buf_len(buf);
402 buf->buf = xrealloc(buf->buf, nsize);
403 buf->e = buf->buf + len + 1;
404 buf->l = buf->buf + nsize - 5;
405 buf->s = buf->buf + 1;
406 }
407
408 static void
409 buf_reserve(struct buffer *buf, size_t n)
410 {
411 if (buf->e + n >= buf->l)
412 buf_expand(buf, n);
413 }
414
415 static void
416 buf_add_char(struct buffer *buf, char ch)
417 {
418 buf_reserve(buf, 1);
419 *buf->e++ = ch;
420 }
421
422 static void
423 buf_add_buf(struct buffer *buf, const struct buffer *add)
424 {
425 size_t len = buf_len(add);
426 buf_reserve(buf, len);
427 memcpy(buf->e, add->s, len);
428 buf->e += len;
429 }
430
431 static void
432 buf_terminate(struct buffer *buf)
433 {
434 buf_reserve(buf, 1);
435 *buf->e = '\0';
436 }
437
438 static void
439 buf_reset(struct buffer *buf)
440 {
441 buf->e = buf->s;
442 }
443
444 static void
445 main_init_globals(void)
446 {
447 found_err = false;
448
449 ps.s_ttype[0] = stmt;
450 ps.last_nl = true;
451 ps.last_token = semicolon;
452 buf_init(&com);
453 buf_init(&lab);
454 buf_init(&code);
455 buf_init(&token);
456
457 opt.else_if = true; /* XXX: redundant? */
458
459 inp.buf = xmalloc(10);
460 inp.l = inp.buf + 8;
461 inp.s = inp.e = inp.buf;
462 line_no = 1;
463 had_eof = ps.in_decl = ps.decl_on_line = break_comma = false;
464
465 ps.init_or_struct = false;
466 ps.want_blank = ps.in_stmt = ps.ind_stmt = false;
467 ps.is_case_label = false;
468
469 sc_end = NULL;
470 saved_inp_s = NULL;
471 saved_inp_e = NULL;
472
473 output = NULL;
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, "unknown parameter: %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(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 indent_declaration(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(token_type ttype, bool *force_nl)
654 {
655 if (*force_nl &&
656 ttype != semicolon &&
657 (ttype != 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.last_token == 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.last_token == rparen_or_rbracket)
708 return false;
709 if (ps.last_token != ident && ps.last_token != funcname)
710 return true;
711 if (opt.proc_calls_space)
712 return true;
713 if (ps.keyword == kw_sizeof)
714 return opt.blank_after_sizeof;
715 return ps.keyword != kw_0 && ps.keyword != kw_offsetof;
716 }
717
718 static void
719 process_lparen_or_lbracket(int decl_ind, bool tabs_to_var, bool sp_sw)
720 {
721 if (++ps.p_l_follow == array_length(ps.paren_indents)) {
722 diag(0, "Reached internal limit of %zu unclosed parens",
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.dumped_decl_indent &&
729 ps.procname[0] == '\0' && ps.paren_level == 0) {
730 /* function pointer declarations */
731 indent_declaration(decl_ind, tabs_to_var);
732 ps.dumped_decl_indent = 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 (sp_sw && 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(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.keyword == kw_offsetof || ps.keyword == kw_sizeof)
760 ps.not_cast_mask |= 1 << ps.p_l_follow;
761 }
762
763 static void
764 process_rparen_or_rbracket(bool *sp_sw, bool *force_nl,
765 token_type hd_type)
766 {
767 if ((ps.cast_mask & (1 << ps.p_l_follow) & ~ps.not_cast_mask) != 0) {
768 ps.next_unary = true;
769 ps.cast_mask &= (1 << ps.p_l_follow) - 1;
770 ps.want_blank = opt.space_after_cast;
771 } else
772 ps.want_blank = true;
773 ps.not_cast_mask &= (1 << ps.p_l_follow) - 1;
774
775 if (--ps.p_l_follow < 0) {
776 ps.p_l_follow = 0;
777 diag(0, "Extra %c", *token.s);
778 }
779
780 if (code.e == code.s) /* if the paren starts the line */
781 ps.paren_level = ps.p_l_follow; /* then indent it */
782
783 *code.e++ = token.s[0];
784
785 if (*sp_sw && ps.p_l_follow == 0) { /* check for end of if (...), or some
786 * such */
787 *sp_sw = false;
788 *force_nl = true; /* must force newline after if */
789 ps.next_unary = true;
790 ps.in_stmt = false; /* don't use stmt continuation indentation */
791
792 parse(hd_type); /* let parser worry about if, or whatever */
793 }
794
795 /*
796 * This should ensure that constructs such as main(){...} and int[]{...}
797 * have their braces put in the right place.
798 */
799 ps.search_brace = opt.brace_same_line;
800 }
801
802 static void
803 process_unary_op(int decl_ind, bool tabs_to_var)
804 {
805 if (!ps.dumped_decl_indent && ps.in_decl && !ps.block_init &&
806 ps.procname[0] == '\0' && ps.paren_level == 0) {
807 /* pointer declarations */
808 indent_declaration(decl_ind - (int)buf_len(&token), tabs_to_var);
809 ps.dumped_decl_indent = true;
810 } else if (ps.want_blank)
811 *code.e++ = ' ';
812
813 buf_add_buf(&code, &token);
814 ps.want_blank = false;
815 }
816
817 static void
818 process_binary_op(void)
819 {
820 if (ps.want_blank)
821 buf_add_char(&code, ' ');
822 buf_add_buf(&code, &token);
823 ps.want_blank = true;
824 }
825
826 static void
827 process_postfix_op(void)
828 {
829 *code.e++ = token.s[0];
830 *code.e++ = token.s[1];
831 ps.want_blank = true;
832 }
833
834 static void
835 process_question(int *seen_quest)
836 {
837 (*seen_quest)++;
838 if (ps.want_blank)
839 *code.e++ = ' ';
840 *code.e++ = '?';
841 ps.want_blank = true;
842 }
843
844 static void
845 process_colon(int *seen_quest, bool *force_nl, bool *seen_case)
846 {
847 if (*seen_quest > 0) { /* part of a '?:' operator */
848 --*seen_quest;
849 if (ps.want_blank)
850 *code.e++ = ' ';
851 *code.e++ = ':';
852 ps.want_blank = true;
853 return;
854 }
855
856 if (ps.init_or_struct) { /* bit-field */
857 *code.e++ = ':';
858 ps.want_blank = false;
859 return;
860 }
861
862 buf_add_buf(&lab, &code); /* 'case' or 'default' or named label */
863 buf_add_char(&lab, ':');
864 buf_terminate(&lab);
865 buf_reset(&code);
866
867 ps.in_stmt = false;
868 ps.is_case_label = *seen_case;
869 *force_nl = *seen_case;
870 *seen_case = false;
871 ps.want_blank = false;
872 }
873
874 static void
875 process_semicolon(bool *seen_case, int *seen_quest, int decl_ind,
876 bool tabs_to_var, bool *sp_sw,
877 token_type hd_type,
878 bool *force_nl)
879 {
880 if (ps.decl_nest == 0)
881 ps.init_or_struct = false;
882 *seen_case = false; /* these will only need resetting in an error */
883 *seen_quest = 0;
884 if (ps.last_token == rparen_or_rbracket)
885 ps.in_parameter_declaration = false;
886 ps.cast_mask = 0;
887 ps.not_cast_mask = 0;
888 ps.block_init = false;
889 ps.block_init_level = 0;
890 ps.just_saw_decl--;
891
892 if (ps.in_decl && code.s == code.e && !ps.block_init &&
893 !ps.dumped_decl_indent && ps.paren_level == 0) {
894 /* indent stray semicolons in declarations */
895 indent_declaration(decl_ind - 1, tabs_to_var);
896 ps.dumped_decl_indent = true;
897 }
898
899 ps.in_decl = ps.decl_nest > 0; /* if we were in a first level
900 * structure declaration, we aren't
901 * anymore */
902
903 if ((!*sp_sw || hd_type != for_exprs) && ps.p_l_follow > 0) {
904
905 /*
906 * There were unbalanced parens in the statement. It is a bit
907 * complicated, because the semicolon might be in a for statement.
908 */
909 diag(1, "Unbalanced parens");
910 ps.p_l_follow = 0;
911 if (*sp_sw) { /* this is a check for an if, while, etc. with
912 * unbalanced parens */
913 *sp_sw = false;
914 parse(hd_type); /* don't lose the 'if', or whatever */
915 }
916 }
917 *code.e++ = ';';
918 ps.want_blank = true;
919 ps.in_stmt = (ps.p_l_follow > 0); /* we are no longer in the middle of a
920 * stmt */
921
922 if (!*sp_sw) { /* if not if for (;;) */
923 parse(semicolon); /* let parser know about end of stmt */
924 *force_nl = true; /* force newline after an end of stmt */
925 }
926 }
927
928 static void
929 process_lbrace(bool *force_nl, bool *sp_sw, token_type hd_type,
930 int *di_stack, int di_stack_cap, int *decl_ind)
931 {
932 ps.in_stmt = false; /* don't indent the {} */
933
934 if (!ps.block_init)
935 *force_nl = true; /* force other stuff on same line as '{' onto
936 * new line */
937 else if (ps.block_init_level <= 0)
938 ps.block_init_level = 1;
939 else
940 ps.block_init_level++;
941
942 if (code.s != code.e && !ps.block_init) {
943 if (!opt.brace_same_line) {
944 dump_line();
945 ps.want_blank = false;
946 } else if (ps.in_parameter_declaration && !ps.init_or_struct) {
947 ps.ind_level_follow = 0;
948 if (opt.function_brace_split) { /* dump the line prior to the
949 * brace ... */
950 dump_line();
951 ps.want_blank = false;
952 } else /* add a space between the decl and brace */
953 ps.want_blank = true;
954 }
955 }
956
957 if (ps.in_parameter_declaration)
958 blank_line_before = false;
959
960 if (ps.p_l_follow > 0) { /* check for preceding unbalanced parens */
961 diag(1, "Unbalanced parens");
962 ps.p_l_follow = 0;
963 if (*sp_sw) { /* check for unclosed if, for, etc. */
964 *sp_sw = false;
965 parse(hd_type);
966 ps.ind_level = ps.ind_level_follow;
967 }
968 }
969
970 if (code.s == code.e)
971 ps.ind_stmt = false; /* don't indent the '{' itself */
972 if (ps.in_decl && ps.init_or_struct) {
973 di_stack[ps.decl_nest] = *decl_ind;
974 if (++ps.decl_nest == di_stack_cap) {
975 diag(0, "Reached internal limit of %d struct levels",
976 di_stack_cap);
977 ps.decl_nest--;
978 }
979 } else {
980 ps.decl_on_line = false; /* we can't be in the middle of a
981 * declaration, so don't do special
982 * indentation of comments */
983 if (opt.blanklines_after_decl_at_top && ps.in_parameter_declaration)
984 blank_line_after = true;
985 ps.in_parameter_declaration = false;
986 ps.in_decl = false;
987 }
988
989 *decl_ind = 0;
990 parse(lbrace);
991 if (ps.want_blank)
992 *code.e++ = ' ';
993 ps.want_blank = false;
994 *code.e++ = '{';
995 ps.just_saw_decl = 0;
996 }
997
998 static void
999 process_rbrace(bool *sp_sw, int *decl_ind, const int *di_stack)
1000 {
1001 if (ps.s_ttype[ps.tos] == decl && !ps.block_init) /* semicolons can be
1002 * omitted in
1003 * declarations */
1004 parse(semicolon);
1005
1006 if (ps.p_l_follow != 0) { /* check for unclosed if, for, else. */
1007 diag(1, "Unbalanced parens");
1008 ps.p_l_follow = 0;
1009 *sp_sw = false;
1010 }
1011
1012 ps.just_saw_decl = 0;
1013 ps.block_init_level--;
1014
1015 if (code.s != code.e && !ps.block_init) { /* '}' must be first on line */
1016 if (opt.verbose)
1017 diag(0, "Line broken");
1018 dump_line();
1019 }
1020
1021 *code.e++ = '}';
1022 ps.want_blank = true;
1023 ps.in_stmt = ps.ind_stmt = false;
1024
1025 if (ps.decl_nest > 0) { /* we are in multi-level structure declaration */
1026 *decl_ind = di_stack[--ps.decl_nest];
1027 if (ps.decl_nest == 0 && !ps.in_parameter_declaration)
1028 ps.just_saw_decl = 2;
1029 ps.in_decl = true;
1030 }
1031
1032 blank_line_before = false;
1033 parse(rbrace); /* let parser know about this */
1034 ps.search_brace = opt.cuddle_else
1035 && ps.s_ttype[ps.tos] == if_expr_stmt
1036 && ps.s_ind_level[ps.tos] >= ps.ind_level;
1037
1038 if (ps.tos <= 1 && opt.blanklines_after_procs && ps.decl_nest <= 0)
1039 blank_line_after = true;
1040 }
1041
1042 static void
1043 process_keyword_do(bool *force_nl, bool *last_else)
1044 {
1045 ps.in_stmt = false;
1046
1047 if (code.e != code.s) { /* make sure this starts a line */
1048 if (opt.verbose)
1049 diag(0, "Line broken");
1050 dump_line();
1051 ps.want_blank = false;
1052 }
1053
1054 *force_nl = true; /* following stuff must go onto new line */
1055 *last_else = false;
1056 parse(keyword_do);
1057 }
1058
1059 static void
1060 process_keyword_else(bool *force_nl, bool *last_else)
1061 {
1062 ps.in_stmt = false;
1063
1064 if (code.e != code.s && (!opt.cuddle_else || code.e[-1] != '}')) {
1065 if (opt.verbose)
1066 diag(0, "Line broken");
1067 dump_line(); /* make sure this starts a line */
1068 ps.want_blank = false;
1069 }
1070
1071 *force_nl = true; /* following stuff must go onto new line */
1072 *last_else = true;
1073 parse(keyword_else);
1074 }
1075
1076 static void
1077 process_decl(int *decl_ind, bool *tabs_to_var)
1078 {
1079 parse(decl); /* let parser worry about indentation */
1080
1081 if (ps.last_token == rparen_or_rbracket && ps.tos <= 1) {
1082 if (code.s != code.e) {
1083 dump_line();
1084 ps.want_blank = false;
1085 }
1086 }
1087
1088 if (ps.in_parameter_declaration && opt.indent_parameters &&
1089 ps.decl_nest == 0) {
1090 ps.ind_level = ps.ind_level_follow = 1;
1091 ps.ind_stmt = false;
1092 }
1093
1094 ps.init_or_struct = /* maybe */ true;
1095 ps.in_decl = ps.decl_on_line = ps.last_token != type_def;
1096 if (ps.decl_nest <= 0)
1097 ps.just_saw_decl = 2;
1098
1099 blank_line_before = false;
1100
1101 int len = (int)buf_len(&token) + 1;
1102 int ind = ps.ind_level == 0 || ps.decl_nest > 0
1103 ? opt.decl_indent /* global variable or local member */
1104 : opt.local_decl_indent; /* local variable */
1105 *decl_ind = ind > 0 ? ind : len;
1106 *tabs_to_var = opt.use_tabs && ind > 0;
1107 }
1108
1109 static void
1110 process_ident(token_type ttype, int decl_ind, bool tabs_to_var,
1111 bool *sp_sw, bool *force_nl, token_type hd_type)
1112 {
1113 if (ps.in_decl) {
1114 if (ttype == funcname) {
1115 ps.in_decl = false;
1116 if (opt.procnames_start_line && code.s != code.e) {
1117 *code.e = '\0';
1118 dump_line();
1119 } else if (ps.want_blank) {
1120 *code.e++ = ' ';
1121 }
1122 ps.want_blank = false;
1123
1124 } else if (!ps.block_init && !ps.dumped_decl_indent &&
1125 ps.paren_level == 0) { /* if we are in a declaration, we must
1126 * indent identifier */
1127 indent_declaration(decl_ind, tabs_to_var);
1128 ps.dumped_decl_indent = true;
1129 ps.want_blank = false;
1130 }
1131
1132 } else if (*sp_sw && ps.p_l_follow == 0) {
1133 *sp_sw = false;
1134 *force_nl = true;
1135 ps.next_unary = true;
1136 ps.in_stmt = false;
1137 parse(hd_type);
1138 }
1139 }
1140
1141 static void
1142 copy_token(void)
1143 {
1144 if (ps.want_blank)
1145 buf_add_char(&code, ' ');
1146 buf_add_buf(&code, &token);
1147 }
1148
1149 static void
1150 process_string_prefix(void)
1151 {
1152 copy_token();
1153 ps.want_blank = false;
1154 }
1155
1156 static void
1157 process_period(void)
1158 {
1159 if (code.e[-1] == ',')
1160 *code.e++ = ' ';
1161 *code.e++ = '.';
1162 ps.want_blank = false;
1163 }
1164
1165 static void
1166 process_comma(int decl_ind, bool tabs_to_var, bool *force_nl)
1167 {
1168 ps.want_blank = code.s != code.e; /* only put blank after comma if comma
1169 * does not start the line */
1170
1171 if (ps.in_decl && ps.procname[0] == '\0' && !ps.block_init &&
1172 !ps.dumped_decl_indent && ps.paren_level == 0) {
1173 /* indent leading commas and not the actual identifiers */
1174 indent_declaration(decl_ind - 1, tabs_to_var);
1175 ps.dumped_decl_indent = true;
1176 }
1177
1178 *code.e++ = ',';
1179
1180 if (ps.p_l_follow == 0) {
1181 if (ps.block_init_level <= 0)
1182 ps.block_init = false;
1183 if (break_comma && (opt.break_after_comma ||
1184 indentation_after_range(
1185 compute_code_indent(), code.s, code.e)
1186 >= opt.max_line_length - opt.tabsize))
1187 *force_nl = true;
1188 }
1189 }
1190
1191 /* move the whole line to the 'label' buffer */
1192 static void
1193 read_preprocessing_line(void)
1194 {
1195 enum {
1196 PLAIN, STR, CHR, COMM
1197 } state;
1198
1199 buf_add_char(&lab, '#');
1200
1201 state = PLAIN;
1202 int com_start = 0, com_end = 0;
1203
1204 while (is_hspace(*inp.s))
1205 inbuf_skip();
1206
1207 while (*inp.s != '\n' || (state == COMM && !had_eof)) {
1208 buf_reserve(&lab, 2);
1209 *lab.e++ = inbuf_next();
1210 switch (lab.e[-1]) {
1211 case '\\':
1212 if (state != COMM)
1213 *lab.e++ = inbuf_next();
1214 break;
1215 case '/':
1216 if (*inp.s == '*' && state == PLAIN) {
1217 state = COMM;
1218 *lab.e++ = *inp.s++;
1219 com_start = (int)buf_len(&lab) - 2;
1220 }
1221 break;
1222 case '"':
1223 if (state == STR)
1224 state = PLAIN;
1225 else if (state == PLAIN)
1226 state = STR;
1227 break;
1228 case '\'':
1229 if (state == CHR)
1230 state = PLAIN;
1231 else if (state == PLAIN)
1232 state = CHR;
1233 break;
1234 case '*':
1235 if (*inp.s == '/' && state == COMM) {
1236 state = PLAIN;
1237 *lab.e++ = *inp.s++;
1238 com_end = (int)buf_len(&lab);
1239 }
1240 break;
1241 }
1242 }
1243
1244 while (lab.e > lab.s && is_hspace(lab.e[-1]))
1245 lab.e--;
1246 if (lab.e - lab.s == com_end && saved_inp_s == NULL) {
1247 /* comment on preprocessor line */
1248 if (sc_end == NULL) { /* if this is the first comment, we must set
1249 * up the buffer */
1250 save_com = sc_buf;
1251 sc_end = save_com;
1252 } else {
1253 *sc_end++ = '\n'; /* add newline between comments */
1254 *sc_end++ = ' ';
1255 --line_no;
1256 }
1257 if (sc_end - save_com + com_end - com_start > sc_size)
1258 errx(1, "input too long");
1259 memmove(sc_end, lab.s + com_start, (size_t)(com_end - com_start));
1260 sc_end += com_end - com_start;
1261 lab.e = lab.s + com_start;
1262 while (lab.e > lab.s && is_hspace(lab.e[-1]))
1263 lab.e--;
1264 saved_inp_s = inp.s; /* save current input buffer */
1265 saved_inp_e = inp.e;
1266 inp.s = save_com; /* fix so that subsequent calls to lexi will
1267 * take tokens out of save_com */
1268 *sc_end++ = ' '; /* add trailing blank, just in case */
1269 inp.e = sc_end;
1270 sc_end = NULL;
1271 debug_println("switched inp.s to save_com");
1272 }
1273 buf_terminate(&lab);
1274 }
1275
1276 static void
1277 process_preprocessing(void)
1278 {
1279 if (com.s != com.e || lab.s != lab.e || code.s != code.e)
1280 dump_line();
1281
1282 read_preprocessing_line();
1283
1284 ps.is_case_label = false;
1285
1286 if (strncmp(lab.s, "#if", 3) == 0) { /* also ifdef, ifndef */
1287 if ((size_t)ifdef_level < array_length(state_stack))
1288 state_stack[ifdef_level++] = ps;
1289 else
1290 diag(1, "#if stack overflow");
1291
1292 } else if (strncmp(lab.s, "#el", 3) == 0) { /* else, elif */
1293 if (ifdef_level <= 0)
1294 diag(1, lab.s[3] == 'i' ? "Unmatched #elif" : "Unmatched #else");
1295 else
1296 ps = state_stack[ifdef_level - 1];
1297
1298 } else if (strncmp(lab.s, "#endif", 6) == 0) {
1299 if (ifdef_level <= 0)
1300 diag(1, "Unmatched #endif");
1301 else
1302 ifdef_level--;
1303
1304 } else {
1305 if (strncmp(lab.s + 1, "pragma", 6) != 0 &&
1306 strncmp(lab.s + 1, "error", 5) != 0 &&
1307 strncmp(lab.s + 1, "line", 4) != 0 &&
1308 strncmp(lab.s + 1, "undef", 5) != 0 &&
1309 strncmp(lab.s + 1, "define", 6) != 0 &&
1310 strncmp(lab.s + 1, "include", 7) != 0) {
1311 diag(1, "Unrecognized cpp directive");
1312 return;
1313 }
1314 }
1315
1316 if (opt.blanklines_around_conditional_compilation) {
1317 blank_line_after = true;
1318 blank_lines_to_output = 0;
1319 } else {
1320 blank_line_after = false;
1321 blank_line_before = false;
1322 }
1323
1324 /*
1325 * subsequent processing of the newline character will cause the line to
1326 * be printed
1327 */
1328 }
1329
1330 static void __attribute__((__noreturn__))
1331 main_loop(void)
1332 {
1333 token_type ttype;
1334 bool force_nl; /* when true, code must be broken */
1335 bool last_else = false; /* true iff last keyword was an else */
1336 int decl_ind; /* current indentation for declarations */
1337 int di_stack[20]; /* a stack of structure indentation levels */
1338 bool tabs_to_var; /* true if using tabs to indent to var name */
1339 bool sp_sw; /* when true, we are in the expression of
1340 * if(...), while(...), etc. */
1341 token_type hd_type = end_of_file; /* the type of statement for if (...),
1342 * for (...), etc */
1343 int seen_quest; /* when this is positive, we have seen a '?'
1344 * without the matching ':' in a <c>?<s>:<s>
1345 * construct */
1346 bool seen_case; /* set to true when we see a 'case', so we
1347 * know what to do with the following colon */
1348
1349 sp_sw = force_nl = false;
1350 decl_ind = 0;
1351 di_stack[ps.decl_nest = 0] = 0;
1352 seen_case = false;
1353 seen_quest = 0;
1354 tabs_to_var = false;
1355
1356 for (;;) { /* this is the main loop. it will go until we
1357 * reach eof */
1358 bool comment_buffered = false;
1359
1360 ttype = lexi(&ps); /* Read the next token. The actual characters
1361 * read are stored in "token". */
1362
1363 /*
1364 * Move newlines and comments following an if (), while (), else, etc.
1365 * up to the start of the following stmt to a buffer. This allows
1366 * proper handling of both kinds of brace placement (-br, -bl) and
1367 * cuddling "else" (-ce).
1368 */
1369 search_brace(&ttype, &force_nl, &comment_buffered, &last_else);
1370
1371 if (ttype == end_of_file) {
1372 process_end_of_file();
1373 /* NOTREACHED */
1374 }
1375
1376 if (ttype == newline || ttype == form_feed || ttype == preprocessing)
1377 force_nl = false;
1378 else if (ttype != comment)
1379 process_comment_in_code(ttype, &force_nl);
1380
1381 buf_reserve(&code, 3); /* space for 2 characters plus '\0' */
1382
1383 switch (ttype) {
1384
1385 case form_feed:
1386 process_form_feed();
1387 break;
1388
1389 case newline:
1390 process_newline();
1391 break;
1392
1393 case lparen_or_lbracket:
1394 process_lparen_or_lbracket(decl_ind, tabs_to_var, sp_sw);
1395 break;
1396
1397 case rparen_or_rbracket:
1398 process_rparen_or_rbracket(&sp_sw, &force_nl, hd_type);
1399 break;
1400
1401 case unary_op:
1402 process_unary_op(decl_ind, tabs_to_var);
1403 break;
1404
1405 case binary_op:
1406 process_binary_op();
1407 break;
1408
1409 case postfix_op:
1410 process_postfix_op();
1411 break;
1412
1413 case question:
1414 process_question(&seen_quest);
1415 break;
1416
1417 case case_label: /* got word 'case' or 'default' */
1418 seen_case = true;
1419 goto copy_token;
1420
1421 case colon:
1422 process_colon(&seen_quest, &force_nl, &seen_case);
1423 break;
1424
1425 case semicolon:
1426 process_semicolon(&seen_case, &seen_quest, decl_ind, tabs_to_var,
1427 &sp_sw, hd_type, &force_nl);
1428 break;
1429
1430 case lbrace:
1431 process_lbrace(&force_nl, &sp_sw, hd_type, di_stack,
1432 (int)array_length(di_stack), &decl_ind);
1433 break;
1434
1435 case rbrace:
1436 process_rbrace(&sp_sw, &decl_ind, di_stack);
1437 break;
1438
1439 case switch_expr: /* got keyword "switch" */
1440 sp_sw = true;
1441 hd_type = switch_expr; /* keep this for when we have seen the
1442 * expression */
1443 goto copy_token;
1444
1445 case keyword_for_if_while:
1446 sp_sw = true; /* the interesting stuff is done after the
1447 * expression is scanned */
1448 hd_type = *token.s == 'i' ? if_expr :
1449 *token.s == 'w' ? while_expr : for_exprs;
1450
1451 /* remember the type of header for later use by parser */
1452 goto copy_token;
1453
1454 case keyword_do_else:
1455 if (*token.s == 'd')
1456 process_keyword_do(&force_nl, &last_else);
1457 else
1458 process_keyword_else(&force_nl, &last_else);
1459 goto copy_token;
1460
1461 case type_def:
1462 case storage_class:
1463 blank_line_before = false;
1464 goto copy_token;
1465
1466 case keyword_struct_union_enum:
1467 if (ps.p_l_follow > 0)
1468 goto copy_token;
1469 /* FALLTHROUGH */
1470 case decl: /* a declaration type (int, etc.) */
1471 process_decl(&decl_ind, &tabs_to_var);
1472 goto copy_token;
1473
1474 case funcname:
1475 case ident: /* an identifier, constant or string */
1476 process_ident(ttype, decl_ind, tabs_to_var, &sp_sw, &force_nl,
1477 hd_type);
1478 copy_token:
1479 copy_token();
1480 if (ttype != funcname)
1481 ps.want_blank = true;
1482 break;
1483
1484 case string_prefix:
1485 process_string_prefix();
1486 break;
1487
1488 case period:
1489 process_period();
1490 break;
1491
1492 case comma:
1493 process_comma(decl_ind, tabs_to_var, &force_nl);
1494 break;
1495
1496 case preprocessing: /* the initial '#' */
1497 process_preprocessing();
1498 break;
1499
1500 case comment: /* the initial '/' '*' or '//' of a comment */
1501 process_comment();
1502 break;
1503
1504 default:
1505 break;
1506 }
1507
1508 *code.e = '\0';
1509 if (ttype != comment && ttype != newline && ttype != preprocessing)
1510 ps.last_token = ttype;
1511 }
1512 }
1513
1514 int
1515 main(int argc, char **argv)
1516 {
1517 main_init_globals();
1518 main_parse_command_line(argc, argv);
1519 #if HAVE_CAPSICUM
1520 init_capsicum();
1521 #endif
1522 main_prepare_parsing();
1523 main_loop();
1524 }
1525
1526 #ifdef debug
1527 void
1528 debug_printf(const char *fmt, ...)
1529 {
1530 FILE *f = output == stdout ? stderr : stdout;
1531 va_list ap;
1532
1533 va_start(ap, fmt);
1534 vfprintf(f, fmt, ap);
1535 va_end(ap);
1536 }
1537
1538 void
1539 debug_println(const char *fmt, ...)
1540 {
1541 FILE *f = output == stdout ? stderr : stdout;
1542 va_list ap;
1543
1544 va_start(ap, fmt);
1545 vfprintf(f, fmt, ap);
1546 va_end(ap);
1547 fprintf(f, "\n");
1548 }
1549
1550 void
1551 debug_vis_range(const char *prefix, const char *s, const char *e,
1552 const char *suffix)
1553 {
1554 debug_printf("%s", prefix);
1555 for (const char *p = s; p < e; p++) {
1556 if (isprint((unsigned char)*p) && *p != '\\' && *p != '"')
1557 debug_printf("%c", *p);
1558 else if (*p == '\n')
1559 debug_printf("\\n");
1560 else if (*p == '\t')
1561 debug_printf("\\t");
1562 else
1563 debug_printf("\\x%02x", *p);
1564 }
1565 debug_printf("%s", suffix);
1566 }
1567 #endif
1568
1569 static void *
1570 nonnull(void *p)
1571 {
1572 if (p == NULL)
1573 err(EXIT_FAILURE, NULL);
1574 return p;
1575 }
1576
1577 void *
1578 xmalloc(size_t size)
1579 {
1580 return nonnull(malloc(size));
1581 }
1582
1583 void *
1584 xrealloc(void *p, size_t new_size)
1585 {
1586 return nonnull(realloc(p, new_size));
1587 }
1588
1589 char *
1590 xstrdup(const char *s)
1591 {
1592 return nonnull(strdup(s));
1593 }
1594