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