indent.c revision 1.180 1 /* $NetBSD: indent.c,v 1.180 2021/10/30 09:42:31 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.180 2021/10/30 09:42:31 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_load_profiles(int argc, char **argv)
523 {
524 const char *profile_name = NULL;
525
526 for (int i = 1; i < argc; ++i) {
527 const char *arg = argv[i];
528
529 if (strcmp(arg, "-npro") == 0)
530 return;
531 if (arg[0] == '-' && arg[1] == 'P' && arg[2] != '\0')
532 profile_name = arg + 2;
533 }
534 load_profiles(profile_name);
535 }
536
537 static void
538 main_parse_command_line(int argc, char **argv)
539 {
540 for (int i = 1; i < argc; ++i) {
541 const char *arg = argv[i];
542
543 if (arg[0] == '-') {
544 set_option(arg, "Command line");
545
546 } else if (input == NULL) {
547 in_name = arg;
548 input = fopen(in_name, "r");
549 if (input == NULL)
550 err(1, "%s", in_name);
551
552 } else if (output == NULL) {
553 out_name = arg;
554 if (strcmp(in_name, out_name) == 0)
555 errx(1, "input and output files must be different");
556 output = fopen(out_name, "w");
557 if (output == NULL)
558 err(1, "%s", out_name);
559
560 } else
561 errx(1, "too many arguments: %s", arg);
562 }
563
564 if (input == NULL)
565 input = stdin;
566 if (output == NULL) {
567 if (input == stdin)
568 output = stdout;
569 else {
570 out_name = in_name;
571 bakcopy();
572 }
573 }
574
575 if (opt.comment_column <= 1)
576 opt.comment_column = 2; /* don't put normal comments before column 2 */
577 if (opt.block_comment_max_line_length <= 0)
578 opt.block_comment_max_line_length = opt.max_line_length;
579 if (opt.local_decl_indent < 0) /* if not specified by user, set this */
580 opt.local_decl_indent = opt.decl_indent;
581 if (opt.decl_comment_column <= 0) /* if not specified by user, set this */
582 opt.decl_comment_column = opt.ljust_decl
583 ? (opt.comment_column <= 10 ? 2 : opt.comment_column - 8)
584 : opt.comment_column;
585 if (opt.continuation_indent == 0)
586 opt.continuation_indent = opt.indent_size;
587 }
588
589 static void
590 main_prepare_parsing(void)
591 {
592 inbuf_read_line();
593
594 parse(psym_semicolon);
595
596 int ind = 0;
597 for (const char *p = inp.s;; p++) {
598 if (*p == ' ')
599 ind++;
600 else if (*p == '\t')
601 ind = next_tab(ind);
602 else
603 break;
604 }
605
606 if (ind >= opt.indent_size)
607 ps.ind_level = ps.ind_level_follow = ind / opt.indent_size;
608 }
609
610 static void
611 code_add_decl_indent(int cur_decl_ind, bool tabs_to_var)
612 {
613 int ind = (int)buf_len(&code);
614 char *orig_code_e = code.e;
615
616 /*
617 * get the tab math right for indentations that are not multiples of
618 * tabsize
619 */
620 if ((ps.ind_level * opt.indent_size) % opt.tabsize != 0) {
621 ind += (ps.ind_level * opt.indent_size) % opt.tabsize;
622 cur_decl_ind += (ps.ind_level * opt.indent_size) % opt.tabsize;
623 }
624
625 if (tabs_to_var) {
626 for (int next; (next = next_tab(ind)) <= cur_decl_ind; ind = next)
627 buf_add_char(&code, '\t');
628 }
629
630 for (; ind < cur_decl_ind; ind++)
631 buf_add_char(&code, ' ');
632
633 if (code.e == orig_code_e && ps.want_blank) {
634 *code.e++ = ' ';
635 ps.want_blank = false;
636 }
637 }
638
639 static void __attribute__((__noreturn__))
640 process_end_of_file(void)
641 {
642 if (lab.s != lab.e || code.s != code.e || com.s != com.e)
643 dump_line();
644
645 if (ps.tos > 1) /* check for balanced braces */
646 diag(1, "Stuff missing from end of file");
647
648 if (opt.verbose) {
649 printf("There were %d output lines and %d comments\n",
650 ps.stats.lines, ps.stats.comments);
651 printf("(Lines with comments)/(Lines with code): %6.3f\n",
652 (1.0 * ps.stats.comment_lines) / ps.stats.code_lines);
653 }
654
655 fflush(output);
656 exit(found_err ? EXIT_FAILURE : EXIT_SUCCESS);
657 }
658
659 static void
660 process_comment_in_code(lexer_symbol lsym, bool *force_nl)
661 {
662 if (*force_nl &&
663 lsym != lsym_semicolon &&
664 (lsym != lsym_lbrace || !opt.brace_same_line)) {
665
666 /* we should force a broken line here */
667 if (opt.verbose)
668 diag(0, "Line broken");
669 dump_line();
670 ps.want_blank = false; /* don't insert blank at line start */
671 *force_nl = false;
672 }
673
674 /* add an extra level of indentation; turned off again by a ';' or '}' */
675 ps.in_stmt = true;
676
677 if (com.s != com.e) { /* a comment embedded in a line */
678 buf_add_char(&code, ' ');
679 buf_add_buf(&code, &com);
680 buf_add_char(&code, ' ');
681 buf_terminate(&code);
682 buf_reset(&com);
683 ps.want_blank = false;
684 }
685 }
686
687 static void
688 process_form_feed(void)
689 {
690 dump_line_ff();
691 ps.want_blank = false;
692 }
693
694 static void
695 process_newline(void)
696 {
697 if (ps.prev_token == lsym_comma && ps.p_l_follow == 0 && !ps.block_init &&
698 !opt.break_after_comma && break_comma &&
699 com.s == com.e)
700 goto stay_in_line;
701
702 dump_line();
703 ps.want_blank = false;
704
705 stay_in_line:
706 ++line_no;
707 }
708
709 static bool
710 want_blank_before_lparen(void)
711 {
712 if (!ps.want_blank)
713 return false;
714 if (ps.prev_token == lsym_rparen_or_rbracket)
715 return false;
716 if (ps.prev_token != lsym_ident && ps.prev_token != lsym_funcname)
717 return true;
718 if (opt.proc_calls_space)
719 return true;
720 if (ps.prev_keyword == kw_sizeof)
721 return opt.blank_after_sizeof;
722 return ps.prev_keyword != kw_0 && ps.prev_keyword != kw_offsetof;
723 }
724
725 static void
726 process_lparen_or_lbracket(int decl_ind, bool tabs_to_var, bool spaced_expr)
727 {
728 if (++ps.p_l_follow == array_length(ps.paren_indents)) {
729 diag(0, "Reached internal limit of %zu unclosed parentheses",
730 array_length(ps.paren_indents));
731 ps.p_l_follow--;
732 }
733
734 if (token.s[0] == '(' && ps.in_decl
735 && !ps.block_init && !ps.decl_indent_done &&
736 ps.procname[0] == '\0' && ps.paren_level == 0) {
737 /* function pointer declarations */
738 code_add_decl_indent(decl_ind, tabs_to_var);
739 ps.decl_indent_done = true;
740 } else if (want_blank_before_lparen())
741 *code.e++ = ' ';
742 ps.want_blank = false;
743 *code.e++ = token.s[0];
744
745 ps.paren_indents[ps.p_l_follow - 1] =
746 (short)indentation_after_range(0, code.s, code.e);
747 debug_println("paren_indents[%d] is now %d",
748 ps.p_l_follow - 1, ps.paren_indents[ps.p_l_follow - 1]);
749
750 if (spaced_expr && ps.p_l_follow == 1 && opt.extra_expr_indent
751 && ps.paren_indents[0] < 2 * opt.indent_size) {
752 ps.paren_indents[0] = (short)(2 * opt.indent_size);
753 debug_println("paren_indents[0] is now %d", ps.paren_indents[0]);
754 }
755
756 if (ps.init_or_struct && *token.s == '(' && ps.tos <= 2) {
757 /*
758 * this is a kluge to make sure that declarations will be aligned
759 * right if proc decl has an explicit type on it, i.e. "int a(x) {..."
760 */
761 parse(psym_semicolon); /* I said this was a kluge... */
762 ps.init_or_struct = false;
763 }
764
765 /* parenthesized type following sizeof or offsetof is not a cast */
766 if (ps.prev_keyword == kw_offsetof || ps.prev_keyword == kw_sizeof)
767 ps.not_cast_mask |= 1 << ps.p_l_follow;
768 }
769
770 static void
771 process_rparen_or_rbracket(bool *spaced_expr, bool *force_nl, stmt_head hd)
772 {
773 if ((ps.cast_mask & (1 << ps.p_l_follow) & ~ps.not_cast_mask) != 0) {
774 ps.next_unary = true;
775 ps.cast_mask &= (1 << ps.p_l_follow) - 1;
776 ps.want_blank = opt.space_after_cast;
777 } else
778 ps.want_blank = true;
779 ps.not_cast_mask &= (1 << ps.p_l_follow) - 1;
780
781 if (ps.p_l_follow > 0)
782 ps.p_l_follow--;
783 else
784 diag(0, "Extra '%c'", *token.s);
785
786 if (code.e == code.s) /* if the paren starts the line */
787 ps.paren_level = ps.p_l_follow; /* then indent it */
788
789 *code.e++ = token.s[0];
790
791 if (*spaced_expr && ps.p_l_follow == 0) { /* check for end of 'if
792 * (...)', or some such */
793 *spaced_expr = false;
794 *force_nl = true; /* must force newline after if */
795 ps.next_unary = true;
796 ps.in_stmt = false; /* don't use stmt continuation indentation */
797
798 parse_stmt_head(hd);
799 }
800
801 /*
802 * This should ensure that constructs such as main(){...} and int[]{...}
803 * have their braces put in the right place.
804 */
805 ps.search_stmt = opt.brace_same_line;
806 }
807
808 static void
809 process_unary_op(int decl_ind, bool tabs_to_var)
810 {
811 if (!ps.decl_indent_done && ps.in_decl && !ps.block_init &&
812 ps.procname[0] == '\0' && ps.paren_level == 0) {
813 /* pointer declarations */
814 code_add_decl_indent(decl_ind - (int)buf_len(&token), tabs_to_var);
815 ps.decl_indent_done = true;
816 } else if (ps.want_blank)
817 *code.e++ = ' ';
818
819 buf_add_buf(&code, &token);
820 ps.want_blank = false;
821 }
822
823 static void
824 process_binary_op(void)
825 {
826 if (!ps.prev_newline && buf_len(&code) > 0)
827 buf_add_char(&code, ' ');
828 buf_add_buf(&code, &token);
829 ps.want_blank = true;
830 }
831
832 static void
833 process_postfix_op(void)
834 {
835 *code.e++ = token.s[0];
836 *code.e++ = token.s[1];
837 ps.want_blank = true;
838 }
839
840 static void
841 process_question(int *quest_level)
842 {
843 (*quest_level)++;
844 if (ps.want_blank)
845 *code.e++ = ' ';
846 *code.e++ = '?';
847 ps.want_blank = true;
848 }
849
850 static void
851 process_colon(int *quest_level, bool *force_nl, bool *seen_case)
852 {
853 if (*quest_level > 0) { /* part of a '?:' operator */
854 --*quest_level;
855 if (ps.want_blank)
856 *code.e++ = ' ';
857 *code.e++ = ':';
858 ps.want_blank = true;
859 return;
860 }
861
862 if (ps.init_or_struct) { /* bit-field */
863 *code.e++ = ':';
864 ps.want_blank = false;
865 return;
866 }
867
868 buf_add_buf(&lab, &code); /* 'case' or 'default' or named label */
869 buf_add_char(&lab, ':');
870 buf_terminate(&lab);
871 buf_reset(&code);
872
873 ps.in_stmt = false;
874 ps.is_case_label = *seen_case;
875 *force_nl = *seen_case;
876 *seen_case = false;
877 ps.want_blank = false;
878 }
879
880 static void
881 process_semicolon(bool *seen_case, int *quest_level, int decl_ind,
882 bool tabs_to_var, bool *spaced_expr, stmt_head hd, bool *force_nl)
883 {
884 if (ps.decl_nest == 0)
885 ps.init_or_struct = false;
886 *seen_case = false; /* these will only need resetting in an error */
887 *quest_level = 0;
888 if (ps.prev_token == lsym_rparen_or_rbracket)
889 ps.in_parameter_declaration = false;
890 ps.cast_mask = 0;
891 ps.not_cast_mask = 0;
892 ps.block_init = false;
893 ps.block_init_level = 0;
894 ps.just_saw_decl--;
895
896 if (ps.in_decl && code.s == code.e && !ps.block_init &&
897 !ps.decl_indent_done && ps.paren_level == 0) {
898 /* indent stray semicolons in declarations */
899 code_add_decl_indent(decl_ind - 1, tabs_to_var);
900 ps.decl_indent_done = true;
901 }
902
903 ps.in_decl = ps.decl_nest > 0; /* if we were in a first level
904 * structure declaration, we aren't
905 * anymore */
906
907 if ((!*spaced_expr || hd != hd_for) && ps.p_l_follow > 0) {
908
909 /*
910 * There were unbalanced parentheses in the statement. It is a bit
911 * complicated, because the semicolon might be in a for statement.
912 */
913 diag(1, "Unbalanced parentheses");
914 ps.p_l_follow = 0;
915 if (*spaced_expr) { /* 'if', 'while', etc. */
916 *spaced_expr = false;
917 parse_stmt_head(hd);
918 }
919 }
920 *code.e++ = ';';
921 ps.want_blank = true;
922 ps.in_stmt = ps.p_l_follow > 0;
923
924 if (!*spaced_expr) { /* if not if for (;;) */
925 parse(psym_semicolon); /* let parser know about end of stmt */
926 *force_nl = true; /* force newline after an end of stmt */
927 }
928 }
929
930 static void
931 process_lbrace(bool *force_nl, bool *spaced_expr, stmt_head hd,
932 int *di_stack, int di_stack_cap, int *decl_ind)
933 {
934 ps.in_stmt = false; /* don't indent the {} */
935
936 if (!ps.block_init)
937 *force_nl = true; /* force other stuff on same line as '{' onto
938 * new line */
939 else if (ps.block_init_level <= 0)
940 ps.block_init_level = 1;
941 else
942 ps.block_init_level++;
943
944 if (code.s != code.e && !ps.block_init) {
945 if (!opt.brace_same_line) {
946 dump_line();
947 ps.want_blank = false;
948 } else if (ps.in_parameter_declaration && !ps.init_or_struct) {
949 ps.ind_level_follow = 0;
950 if (opt.function_brace_split) { /* dump the line prior to the
951 * brace ... */
952 dump_line();
953 ps.want_blank = false;
954 } else /* add a space between the decl and brace */
955 ps.want_blank = true;
956 }
957 }
958
959 if (ps.in_parameter_declaration)
960 blank_line_before = false;
961
962 if (ps.p_l_follow > 0) {
963 diag(1, "Unbalanced parentheses");
964 ps.p_l_follow = 0;
965 if (*spaced_expr) { /* check for unclosed 'if', 'for', etc. */
966 *spaced_expr = false;
967 parse_stmt_head(hd);
968 ps.ind_level = ps.ind_level_follow;
969 }
970 }
971
972 if (code.s == code.e)
973 ps.ind_stmt = false; /* don't indent the '{' itself */
974 if (ps.in_decl && ps.init_or_struct) {
975 di_stack[ps.decl_nest] = *decl_ind;
976 if (++ps.decl_nest == di_stack_cap) {
977 diag(0, "Reached internal limit of %d struct levels",
978 di_stack_cap);
979 ps.decl_nest--;
980 }
981 } else {
982 ps.decl_on_line = false; /* we can't be in the middle of a
983 * declaration, so don't do special
984 * indentation of comments */
985 if (opt.blanklines_after_decl_at_top && ps.in_parameter_declaration)
986 blank_line_after = true;
987 ps.in_parameter_declaration = false;
988 ps.in_decl = false;
989 }
990
991 *decl_ind = 0;
992 parse(psym_lbrace);
993 if (ps.want_blank)
994 *code.e++ = ' ';
995 ps.want_blank = false;
996 *code.e++ = '{';
997 ps.just_saw_decl = 0;
998 }
999
1000 static void
1001 process_rbrace(bool *spaced_expr, int *decl_ind, const int *di_stack)
1002 {
1003 if (ps.s_sym[ps.tos] == psym_decl && !ps.block_init) {
1004 /* semicolons can be omitted in declarations */
1005 parse(psym_semicolon);
1006 }
1007
1008 if (ps.p_l_follow > 0) { /* check for unclosed if, for, else. */
1009 diag(1, "Unbalanced parentheses");
1010 ps.p_l_follow = 0;
1011 *spaced_expr = false;
1012 }
1013
1014 ps.just_saw_decl = 0;
1015 ps.block_init_level--;
1016
1017 if (code.s != code.e && !ps.block_init) { /* '}' must be first on line */
1018 if (opt.verbose)
1019 diag(0, "Line broken");
1020 dump_line();
1021 }
1022
1023 *code.e++ = '}';
1024 ps.want_blank = true;
1025 ps.in_stmt = ps.ind_stmt = false;
1026
1027 if (ps.decl_nest > 0) { /* we are in multi-level structure declaration */
1028 *decl_ind = di_stack[--ps.decl_nest];
1029 if (ps.decl_nest == 0 && !ps.in_parameter_declaration) {
1030 ps.just_saw_decl = 2;
1031 *decl_ind = ps.ind_level == 0
1032 ? opt.decl_indent : opt.local_decl_indent;
1033 }
1034 ps.in_decl = true;
1035 }
1036
1037 blank_line_before = false;
1038 parse(psym_rbrace);
1039 ps.search_stmt = opt.cuddle_else
1040 && ps.s_sym[ps.tos] == psym_if_expr_stmt
1041 && ps.s_ind_level[ps.tos] >= ps.ind_level;
1042
1043 if (ps.tos <= 1 && opt.blanklines_after_procs && ps.decl_nest <= 0)
1044 blank_line_after = true;
1045 }
1046
1047 static void
1048 process_keyword_do(bool *force_nl, bool *last_else)
1049 {
1050 ps.in_stmt = false;
1051
1052 if (code.e != code.s) { /* make sure this starts a line */
1053 if (opt.verbose)
1054 diag(0, "Line broken");
1055 dump_line();
1056 ps.want_blank = false;
1057 }
1058
1059 *force_nl = true; /* following stuff must go onto new line */
1060 *last_else = false;
1061 parse(psym_do);
1062 }
1063
1064 static void
1065 process_keyword_else(bool *force_nl, bool *last_else)
1066 {
1067 ps.in_stmt = false;
1068
1069 if (code.e != code.s && (!opt.cuddle_else || code.e[-1] != '}')) {
1070 if (opt.verbose)
1071 diag(0, "Line broken");
1072 dump_line(); /* make sure this starts a line */
1073 ps.want_blank = false;
1074 }
1075
1076 *force_nl = true; /* following stuff must go onto new line */
1077 *last_else = true;
1078 parse(psym_else);
1079 }
1080
1081 static void
1082 process_type(int *decl_ind, bool *tabs_to_var)
1083 {
1084 parse(psym_decl); /* let the parser worry about indentation */
1085
1086 if (ps.prev_token == lsym_rparen_or_rbracket && ps.tos <= 1) {
1087 if (code.s != code.e) {
1088 dump_line();
1089 ps.want_blank = false;
1090 }
1091 }
1092
1093 if (ps.in_parameter_declaration && opt.indent_parameters &&
1094 ps.decl_nest == 0) {
1095 ps.ind_level = ps.ind_level_follow = 1;
1096 ps.ind_stmt = false;
1097 }
1098
1099 ps.init_or_struct = /* maybe */ true;
1100 ps.in_decl = ps.decl_on_line = ps.prev_token != lsym_typedef;
1101 if (ps.decl_nest <= 0)
1102 ps.just_saw_decl = 2;
1103
1104 blank_line_before = false;
1105
1106 int len = (int)buf_len(&token) + 1;
1107 int ind = ps.ind_level == 0 || ps.decl_nest > 0
1108 ? opt.decl_indent /* global variable or local member */
1109 : opt.local_decl_indent; /* local variable */
1110 *decl_ind = ind > 0 ? ind : len;
1111 *tabs_to_var = opt.use_tabs && ind > 0;
1112 }
1113
1114 static void
1115 process_ident(lexer_symbol lsym, int decl_ind, bool tabs_to_var,
1116 bool *spaced_expr, bool *force_nl, stmt_head hd)
1117 {
1118 if (ps.in_decl) {
1119 if (lsym == lsym_funcname) {
1120 ps.in_decl = false;
1121 if (opt.procnames_start_line && code.s != code.e) {
1122 *code.e = '\0';
1123 dump_line();
1124 } else if (ps.want_blank) {
1125 *code.e++ = ' ';
1126 }
1127 ps.want_blank = false;
1128
1129 } else if (!ps.block_init && !ps.decl_indent_done &&
1130 ps.paren_level == 0) {
1131 code_add_decl_indent(decl_ind, tabs_to_var);
1132 ps.decl_indent_done = true;
1133 ps.want_blank = false;
1134 }
1135
1136 } else if (*spaced_expr && ps.p_l_follow == 0) {
1137 *spaced_expr = false;
1138 *force_nl = true;
1139 ps.next_unary = true;
1140 ps.in_stmt = false;
1141 parse_stmt_head(hd);
1142 }
1143 }
1144
1145 static void
1146 copy_token(void)
1147 {
1148 if (ps.want_blank)
1149 buf_add_char(&code, ' ');
1150 buf_add_buf(&code, &token);
1151 }
1152
1153 static void
1154 process_string_prefix(void)
1155 {
1156 copy_token();
1157 ps.want_blank = false;
1158 }
1159
1160 static void
1161 process_period(void)
1162 {
1163 if (code.e[-1] == ',')
1164 *code.e++ = ' ';
1165 *code.e++ = '.';
1166 ps.want_blank = false;
1167 }
1168
1169 static void
1170 process_comma(int decl_ind, bool tabs_to_var, bool *force_nl)
1171 {
1172 ps.want_blank = code.s != code.e; /* only put blank after comma if comma
1173 * does not start the line */
1174
1175 if (ps.in_decl && ps.procname[0] == '\0' && !ps.block_init &&
1176 !ps.decl_indent_done && ps.paren_level == 0) {
1177 /* indent leading commas and not the actual identifiers */
1178 code_add_decl_indent(decl_ind - 1, tabs_to_var);
1179 ps.decl_indent_done = true;
1180 }
1181
1182 *code.e++ = ',';
1183
1184 if (ps.p_l_follow == 0) {
1185 if (ps.block_init_level <= 0)
1186 ps.block_init = false;
1187 if (break_comma && (opt.break_after_comma ||
1188 indentation_after_range(compute_code_indent(), code.s, code.e)
1189 >= opt.max_line_length - opt.tabsize))
1190 *force_nl = true;
1191 }
1192 }
1193
1194 /* move the whole line to the 'label' buffer */
1195 static void
1196 read_preprocessing_line(void)
1197 {
1198 enum {
1199 PLAIN, STR, CHR, COMM
1200 } state;
1201
1202 buf_add_char(&lab, '#');
1203
1204 state = PLAIN;
1205 int com_start = 0, com_end = 0;
1206
1207 while (ch_isblank(*inp.s))
1208 inbuf_skip();
1209
1210 while (*inp.s != '\n' || (state == COMM && !had_eof)) {
1211 buf_reserve(&lab, 2);
1212 *lab.e++ = inbuf_next();
1213 switch (lab.e[-1]) {
1214 case '\\':
1215 if (state != COMM)
1216 *lab.e++ = inbuf_next();
1217 break;
1218 case '/':
1219 if (*inp.s == '*' && state == PLAIN) {
1220 state = COMM;
1221 *lab.e++ = *inp.s++;
1222 com_start = (int)buf_len(&lab) - 2;
1223 }
1224 break;
1225 case '"':
1226 if (state == STR)
1227 state = PLAIN;
1228 else if (state == PLAIN)
1229 state = STR;
1230 break;
1231 case '\'':
1232 if (state == CHR)
1233 state = PLAIN;
1234 else if (state == PLAIN)
1235 state = CHR;
1236 break;
1237 case '*':
1238 if (*inp.s == '/' && state == COMM) {
1239 state = PLAIN;
1240 *lab.e++ = *inp.s++;
1241 com_end = (int)buf_len(&lab);
1242 }
1243 break;
1244 }
1245 }
1246
1247 while (lab.e > lab.s && ch_isblank(lab.e[-1]))
1248 lab.e--;
1249 if (lab.e - lab.s == com_end && saved_inp_s == NULL) {
1250 /* comment on preprocessor line */
1251 if (sc_end == NULL) { /* if this is the first comment, we must set
1252 * up the buffer */
1253 save_com = sc_buf;
1254 sc_end = save_com;
1255 } else {
1256 *sc_end++ = '\n'; /* add newline between comments */
1257 *sc_end++ = ' ';
1258 --line_no;
1259 }
1260 if (sc_end - save_com + com_end - com_start > sc_size)
1261 errx(1, "input too long");
1262 memmove(sc_end, lab.s + com_start, (size_t)(com_end - com_start));
1263 sc_end += com_end - com_start;
1264 lab.e = lab.s + com_start;
1265 while (lab.e > lab.s && ch_isblank(lab.e[-1]))
1266 lab.e--;
1267 saved_inp_s = inp.s; /* save current input buffer */
1268 saved_inp_e = inp.e;
1269 inp.s = save_com; /* fix so that subsequent calls to lexi will
1270 * take tokens out of save_com */
1271 *sc_end++ = ' '; /* add trailing blank, just in case */
1272 inp.e = sc_end;
1273 sc_end = NULL;
1274 debug_println("switched inp.s to save_com");
1275 }
1276 buf_terminate(&lab);
1277 }
1278
1279 static void
1280 process_preprocessing(void)
1281 {
1282 if (com.s != com.e || lab.s != lab.e || code.s != code.e)
1283 dump_line();
1284
1285 read_preprocessing_line();
1286
1287 ps.is_case_label = false;
1288
1289 if (strncmp(lab.s, "#if", 3) == 0) { /* also ifdef, ifndef */
1290 if ((size_t)ifdef_level < array_length(state_stack))
1291 state_stack[ifdef_level++] = ps;
1292 else
1293 diag(1, "#if stack overflow");
1294
1295 } else if (strncmp(lab.s, "#el", 3) == 0) { /* else, elif */
1296 if (ifdef_level <= 0)
1297 diag(1, lab.s[3] == 'i' ? "Unmatched #elif" : "Unmatched #else");
1298 else
1299 ps = state_stack[ifdef_level - 1];
1300
1301 } else if (strncmp(lab.s, "#endif", 6) == 0) {
1302 if (ifdef_level <= 0)
1303 diag(1, "Unmatched #endif");
1304 else
1305 ifdef_level--;
1306
1307 } else {
1308 if (strncmp(lab.s + 1, "pragma", 6) != 0 &&
1309 strncmp(lab.s + 1, "error", 5) != 0 &&
1310 strncmp(lab.s + 1, "line", 4) != 0 &&
1311 strncmp(lab.s + 1, "undef", 5) != 0 &&
1312 strncmp(lab.s + 1, "define", 6) != 0 &&
1313 strncmp(lab.s + 1, "include", 7) != 0) {
1314 diag(1, "Unrecognized cpp directive");
1315 return;
1316 }
1317 }
1318
1319 if (opt.blanklines_around_conditional_compilation) {
1320 blank_line_after = true;
1321 blank_lines_to_output = 0;
1322 } else {
1323 blank_line_after = false;
1324 blank_line_before = false;
1325 }
1326
1327 /*
1328 * subsequent processing of the newline character will cause the line to
1329 * be printed
1330 */
1331 }
1332
1333 static void __attribute__((__noreturn__))
1334 main_loop(void)
1335 {
1336 bool force_nl = false; /* when true, code must be broken */
1337 bool last_else = false; /* true iff last keyword was an else */
1338 int decl_ind = 0; /* current indentation for declarations */
1339 int di_stack[20]; /* a stack of structure indentation levels */
1340 bool tabs_to_var = false; /* true if using tabs to indent to var name */
1341 bool spaced_expr = false; /* whether we are in the expression of
1342 * if(...), while(...), etc. */
1343 stmt_head hd = hd_0; /* the type of statement for 'if (...)', 'for
1344 * (...)', etc */
1345 int quest_level = 0; /* when this is positive, we have seen a '?'
1346 * without the matching ':' in a '?:'
1347 * expression */
1348 bool seen_case = false; /* set to true when we see a 'case', so we
1349 * know what to do with the following colon */
1350
1351 di_stack[ps.decl_nest = 0] = 0;
1352
1353 for (;;) { /* this is the main loop. it will go until we
1354 * reach eof */
1355 bool comment_buffered = false;
1356
1357 lexer_symbol lsym = lexi(); /* Read the next token. The actual
1358 * characters read are stored in
1359 * "token". */
1360
1361 search_stmt(&lsym, &force_nl, &comment_buffered, &last_else);
1362
1363 if (lsym == lsym_eof) {
1364 process_end_of_file();
1365 /* NOTREACHED */
1366 }
1367
1368 if (lsym == lsym_newline || lsym == lsym_form_feed ||
1369 lsym == lsym_preprocessing)
1370 force_nl = false;
1371 else if (lsym != lsym_comment)
1372 process_comment_in_code(lsym, &force_nl);
1373
1374 buf_reserve(&code, 3); /* space for 2 characters plus '\0' */
1375
1376 switch (lsym) {
1377
1378 case lsym_form_feed:
1379 process_form_feed();
1380 break;
1381
1382 case lsym_newline:
1383 process_newline();
1384 break;
1385
1386 case lsym_lparen_or_lbracket:
1387 process_lparen_or_lbracket(decl_ind, tabs_to_var, spaced_expr);
1388 break;
1389
1390 case lsym_rparen_or_rbracket:
1391 process_rparen_or_rbracket(&spaced_expr, &force_nl, hd);
1392 break;
1393
1394 case lsym_unary_op:
1395 process_unary_op(decl_ind, tabs_to_var);
1396 break;
1397
1398 case lsym_binary_op:
1399 process_binary_op();
1400 break;
1401
1402 case lsym_postfix_op:
1403 process_postfix_op();
1404 break;
1405
1406 case lsym_question:
1407 process_question(&quest_level);
1408 break;
1409
1410 case lsym_case_label:
1411 seen_case = true;
1412 goto copy_token;
1413
1414 case lsym_colon:
1415 process_colon(&quest_level, &force_nl, &seen_case);
1416 break;
1417
1418 case lsym_semicolon:
1419 process_semicolon(&seen_case, &quest_level, decl_ind, tabs_to_var,
1420 &spaced_expr, hd, &force_nl);
1421 break;
1422
1423 case lsym_lbrace:
1424 process_lbrace(&force_nl, &spaced_expr, hd, di_stack,
1425 (int)array_length(di_stack), &decl_ind);
1426 break;
1427
1428 case lsym_rbrace:
1429 process_rbrace(&spaced_expr, &decl_ind, di_stack);
1430 break;
1431
1432 case lsym_switch:
1433 spaced_expr = true; /* the interesting stuff is done after the
1434 * expressions are scanned */
1435 hd = hd_switch; /* remember the type of header for later use
1436 * by the parser */
1437 goto copy_token;
1438
1439 case lsym_for:
1440 spaced_expr = true;
1441 hd = hd_for;
1442 goto copy_token;
1443
1444 case lsym_if:
1445 spaced_expr = true;
1446 hd = hd_if;
1447 goto copy_token;
1448
1449 case lsym_while:
1450 spaced_expr = true;
1451 hd = hd_while;
1452 goto copy_token;
1453
1454 case lsym_do:
1455 process_keyword_do(&force_nl, &last_else);
1456 goto copy_token;
1457
1458 case lsym_else:
1459 process_keyword_else(&force_nl, &last_else);
1460 goto copy_token;
1461
1462 case lsym_typedef:
1463 case lsym_storage_class:
1464 blank_line_before = false;
1465 goto copy_token;
1466
1467 case lsym_tag:
1468 if (ps.p_l_follow > 0)
1469 goto copy_token;
1470 /* FALLTHROUGH */
1471 case lsym_type:
1472 process_type(&decl_ind, &tabs_to_var);
1473 goto copy_token;
1474
1475 case lsym_funcname:
1476 case lsym_ident:
1477 process_ident(lsym, decl_ind, tabs_to_var, &spaced_expr,
1478 &force_nl, hd);
1479 copy_token:
1480 copy_token();
1481 if (lsym != lsym_funcname)
1482 ps.want_blank = true;
1483 break;
1484
1485 case lsym_string_prefix:
1486 process_string_prefix();
1487 break;
1488
1489 case lsym_period:
1490 process_period();
1491 break;
1492
1493 case lsym_comma:
1494 process_comma(decl_ind, tabs_to_var, &force_nl);
1495 break;
1496
1497 case lsym_preprocessing:
1498 process_preprocessing();
1499 break;
1500
1501 case lsym_comment:
1502 process_comment();
1503 break;
1504
1505 default:
1506 break;
1507 }
1508
1509 *code.e = '\0';
1510 if (lsym != lsym_comment && lsym != lsym_newline &&
1511 lsym != lsym_preprocessing)
1512 ps.prev_token = lsym;
1513 }
1514 }
1515
1516 int
1517 main(int argc, char **argv)
1518 {
1519 main_init_globals();
1520 main_load_profiles(argc, argv);
1521 main_parse_command_line(argc, argv);
1522 #if HAVE_CAPSICUM
1523 init_capsicum();
1524 #endif
1525 main_prepare_parsing();
1526 main_loop();
1527 }
1528
1529 #ifdef debug
1530 void
1531 debug_printf(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 }
1540
1541 void
1542 debug_println(const char *fmt, ...)
1543 {
1544 FILE *f = output == stdout ? stderr : stdout;
1545 va_list ap;
1546
1547 va_start(ap, fmt);
1548 vfprintf(f, fmt, ap);
1549 va_end(ap);
1550 fprintf(f, "\n");
1551 }
1552
1553 void
1554 debug_vis_range(const char *prefix, const char *s, const char *e,
1555 const char *suffix)
1556 {
1557 debug_printf("%s", prefix);
1558 for (const char *p = s; p < e; p++) {
1559 if (*p == '\\' || *p == '"')
1560 debug_printf("\\%c", *p);
1561 else if (isprint((unsigned char)*p))
1562 debug_printf("%c", *p);
1563 else if (*p == '\n')
1564 debug_printf("\\n");
1565 else if (*p == '\t')
1566 debug_printf("\\t");
1567 else
1568 debug_printf("\\x%02x", (unsigned char)*p);
1569 }
1570 debug_printf("%s", suffix);
1571 }
1572 #endif
1573
1574 static void *
1575 nonnull(void *p)
1576 {
1577 if (p == NULL)
1578 err(EXIT_FAILURE, NULL);
1579 return p;
1580 }
1581
1582 void *
1583 xmalloc(size_t size)
1584 {
1585 return nonnull(malloc(size));
1586 }
1587
1588 void *
1589 xrealloc(void *p, size_t new_size)
1590 {
1591 return nonnull(realloc(p, new_size));
1592 }
1593
1594 char *
1595 xstrdup(const char *s)
1596 {
1597 return nonnull(strdup(s));
1598 }
1599