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