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