1 /**	$MirOS: src/usr.bin/indent/io.c,v 1.6 2007/05/06 18:26:18 tg Exp $ */
2 /*	$OpenBSD: io.c,v 1.10 2005/05/15 03:27:04 millert Exp $	*/
3 
4 /*
5  * Copyright (c) 1985 Sun Microsystems, Inc.
6  * Copyright (c) 1980, 1993 The Regents of the University of California.
7  * Copyright (c) 1976 Board of Trustees of the University of Illinois.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <stdio.h>
36 #include <ctype.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <stdarg.h>
40 #include <err.h>
41 #include "indent_globs.h"
42 
43 __SCCSID("@(#)io.c	8.1 (Berkeley) 6/6/93");
44 __RCSID("$MirOS: src/usr.bin/indent/io.c,v 1.6 2007/05/06 18:26:18 tg Exp $");
45 
46 
47 int         comment_open;
48 static int  paren_target;
49 
50 void
dump_line(void)51 dump_line(void)
52 {				/* dump_line is the routine that actually
53 				 * effects the printing of the new source. It
54 				 * prints the label section, followed by the
55 				 * code section with the appropriate nesting
56 				 * level, followed by any comments */
57     int         cur_col, target_col = 0;
58     static int  not_first_line;
59 
60     if (ps.procname[0]) {
61 	if (troff) {
62 	    if (comment_open) {
63 		comment_open = 0;
64 		fprintf(output, ".*/\n");
65 	    }
66 	    fprintf(output, ".Pr \"%s\"\n", ps.procname);
67 	}
68 	ps.ind_level = 0;
69 	ps.procname[0] = 0;
70     }
71     if (s_code == e_code && s_lab == e_lab && s_com == e_com) {
72 	if (suppress_blanklines > 0)
73 	    suppress_blanklines--;
74 	else {
75 	    ps.bl_line = true;
76 	    n_real_blanklines++;
77 	}
78     }
79     else if (!inhibit_formatting) {
80 	suppress_blanklines = 0;
81 	ps.bl_line = false;
82 	if (prefix_blankline_requested && not_first_line) {
83 	    if (swallow_optional_blanklines) {
84 		if (n_real_blanklines == 1)
85 		    n_real_blanklines = 0;
86 	    } else {
87 		if (n_real_blanklines == 0)
88 		    n_real_blanklines = 1;
89 	    }
90 	}
91 	while (--n_real_blanklines >= 0)
92 	    putc('\n', output);
93 	n_real_blanklines = 0;
94 	if (ps.ind_level == 0)
95 	    ps.ind_stmt = 0;	/* this is a class A kludge. dont do
96 				 * additional statement indentation if we are
97 				 * at bracket level 0 */
98 
99 	if (e_lab != s_lab || e_code != s_code)
100 	    ++code_lines;	/* keep count of lines with code */
101 
102 
103 	if (e_lab != s_lab) {	/* print lab, if any */
104 	    if (comment_open) {
105 		comment_open = 0;
106 		fprintf(output, ".*/\n");
107 	    }
108 	    while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
109 		e_lab--;
110 	    cur_col = pad_output(1, compute_label_target());
111 	    if (s_lab[0] == '#' && (strncmp(s_lab, "#else", 5) == 0
112 				    || strncmp(s_lab, "#endif", 6) == 0)) {
113 		char *s = s_lab;
114 		if (e_lab[-1] == '\n')
115 			e_lab--;
116 		do
117 			putc(*s++, output);
118 		while (s < e_lab && 'a' <= *s && *s<='z');
119 		while ((*s == ' ' || *s == '\t') && s < e_lab)
120 		    s++;
121 		if (s < e_lab)
122 		    fprintf(output, s[0]=='/' && s[1]=='*' ? "\t%.*s" : "\t/* %.*s */",
123 			    (int)(e_lab - s), s);
124 	    }
125 	    else fprintf(output, "%.*s", (int)(e_lab - s_lab), s_lab);
126 	    cur_col = count_spaces(cur_col, s_lab);
127 	}
128 	else
129 	    cur_col = 1;	/* there is no label section */
130 
131 	ps.pcase = false;
132 
133 	if (s_code != e_code) {	/* print code section, if any */
134 	    char *p;
135 
136 	    if (comment_open) {
137 		comment_open = 0;
138 		fprintf(output, ".*/\n");
139 	    }
140 	    target_col = compute_code_target();
141 	    {
142 		int  i;
143 
144 		for (i = 0; i < ps.p_l_follow; i++)
145 		    if (ps.paren_indents[i] >= 0)
146 			ps.paren_indents[i] = -(ps.paren_indents[i] + target_col);
147 	    }
148 	    cur_col = pad_output(cur_col, target_col);
149 	    for (p = s_code; p < e_code; p++)
150 #if 0
151 		if (*p == (char) 0200)
152 		    fprintf(output, "%d", target_col * 7);
153 		else
154 #endif
155 		    putc(*p, output);
156 	    cur_col = count_spaces(cur_col, s_code);
157 	}
158 	if (s_com != e_com) {
159 	    if (troff) {
160 		int   all_here = 0;
161 		char *p;
162 
163 		if (e_com[-1] == '/' && e_com[-2] == '*')
164 		    e_com -= 2, all_here++;
165 		while (e_com > s_com && e_com[-1] == ' ')
166 		    e_com--;
167 		*e_com = 0;
168 		p = s_com;
169 		while (*p == ' ')
170 		    p++;
171 		if (p[0] == '/' && p[1] == '*')
172 		    p += 2, all_here++;
173 		else if (p[0] == '*')
174 		    p += p[1] == '/' ? 2 : 1;
175 		while (*p == ' ')
176 		    p++;
177 		if (*p == 0)
178 		    goto inhibit_newline;
179 		if (comment_open < 2 && ps.box_com) {
180 		    comment_open = 0;
181 		    fprintf(output, ".*/\n");
182 		}
183 		if (comment_open == 0) {
184 		    if ('a' <= *p && *p <= 'z')
185 			*p = *p + 'A' - 'a';
186 		    if (e_com - p < 50 && all_here == 2) {
187 			char *follow = p;
188 			fprintf(output, "\n.nr C! \\w\1");
189 			while (follow < e_com) {
190 			    switch (*follow) {
191 			    case '\n':
192 				putc(' ', output);
193 			    case 1:
194 				break;
195 			    case '\\':
196 				putc('\\', output);
197 			    default:
198 				putc(*follow, output);
199 			    }
200 			    follow++;
201 			}
202 			putc(1, output);
203 		    }
204 		    fprintf(output, "\n./* %dp %d %dp\n",
205 			    ps.com_col * 7,
206 			    (s_code != e_code || s_lab != e_lab) - ps.box_com,
207 			    target_col * 7);
208 		}
209 		comment_open = 1 + ps.box_com;
210 		while (*p) {
211 		    if (*p == BACKSLASH)
212 			putc(BACKSLASH, output);
213 		    putc(*p++, output);
214 		}
215 	    } else {		/* print comment, if any */
216 		int   target = ps.com_col;
217 		char *com_st = s_com;
218 
219 		target += ps.comment_delta;
220 		while (*com_st == '\t')
221 		    com_st++, target += 8;	/* ? */
222 		while (target <= 0)
223 		    if (*com_st == ' ')
224 			target++, com_st++;
225 		    else if (*com_st == '\t')
226 			target = ((target - 1) & ~7) + 9, com_st++;
227 		    else
228 			target = 1;
229 		if (cur_col > target) {	/* if comment cant fit on this line,
230 					 * put it on next line */
231 		    putc('\n', output);
232 		    cur_col = 1;
233 		    ++ps.out_lines;
234 		}
235 		while (e_com > com_st && isspace(e_com[-1]))
236 		    e_com--;
237 		cur_col = pad_output(cur_col, target);
238 		if (!ps.box_com) {
239 		    if (star_comment_cont && (com_st[1] != '*' || e_com <= com_st + 1)) {
240 			if (com_st[1] == ' ' && com_st[0] == ' ' && e_com > com_st + 1)
241 			    com_st[1] = '*';
242 			else
243 			    fwrite(" * ", com_st[0] == '\t' ? 2 : com_st[0] == '*' ? 1 : 3, 1, output);
244 		    }
245 		}
246 		fwrite(com_st, e_com - com_st, 1, output);
247 		ps.comment_delta = ps.n_comment_delta;
248 		cur_col = count_spaces(cur_col, com_st);
249 		++ps.com_lines;	/* count lines with comments */
250 	    }
251 	}
252 	if (ps.use_ff)
253 	    putc('\014', output);
254 	else
255 	    putc('\n', output);
256 inhibit_newline:
257 	++ps.out_lines;
258 	if (ps.just_saw_decl == 1 && blanklines_after_declarations) {
259 	    prefix_blankline_requested = 1;
260 	    ps.just_saw_decl = 0;
261 	}
262 	else
263 	    prefix_blankline_requested = postfix_blankline_requested;
264 	postfix_blankline_requested = 0;
265     }
266     ps.decl_on_line = ps.in_decl;	/* if we are in the middle of a
267 					 * declaration, remember that fact for
268 					 * proper comment indentation */
269     ps.ind_stmt = ps.in_stmt & ~ps.in_decl;	/* next line should be
270 						 * indented if we have not
271 						 * completed this stmt and if
272 						 * we are not in the middle of
273 						 * a declaration */
274     ps.use_ff = false;
275     ps.dumped_decl_indent = 0;
276     *(e_lab = s_lab) = '\0';	/* reset buffers */
277     *(e_code = s_code) = '\0';
278     *(e_com = s_com) = '\0';
279     ps.ind_level = ps.i_l_follow;
280     ps.paren_level = ps.p_l_follow;
281     paren_target = -ps.paren_indents[ps.paren_level - 1];
282     not_first_line = 1;
283     return;
284 }
285 
286 int
compute_code_target(void)287 compute_code_target(void)
288 {
289     int target_col;
290 
291     target_col = ps.ind_size * ps.ind_level + 1;
292     if (ps.paren_level)
293 	if (!lineup_to_parens)
294 	    target_col += continuation_indent *
295 		(lineup_indent ? ps.paren_level : 1);
296 	else {
297 	    int    w;
298 	    int    t = paren_target;
299 
300 	    if ((w = count_spaces(t, s_code) - max_col) > 0
301 		    && count_spaces(target_col, s_code) <= max_col) {
302 		t -= w + 1;
303 		if (t > target_col)
304 		    target_col = t;
305 	    }
306 	    else
307 		target_col = t;
308 	}
309     else if (ps.ind_stmt)
310 	target_col += continuation_indent;
311     return target_col;
312 }
313 
314 int
compute_label_target(void)315 compute_label_target(void)
316 {
317     return
318 	ps.pcase ? (int) (case_ind * ps.ind_size) + 1
319 	: *s_lab == '#' ? 1
320 	: ps.ind_size * (ps.ind_level - label_offset) + 1;
321 }
322 
323 
324 /*
325  * Copyright (C) 1976 by the Board of Trustees of the University of Illinois
326  *
327  * All rights reserved
328  *
329  *
330  * NAME: fill_buffer
331  *
332  * FUNCTION: Reads one block of input into input_buffer
333  *
334  * HISTORY: initial coding 	November 1976	D A Willcox of CAC 1/7/77 A
335  * Willcox of CAC	Added check for switch back to partly full input
336  * buffer from temporary buffer
337  *
338  */
339 void
fill_buffer(void)340 fill_buffer(void)
341 {				/* this routine reads stuff from the input */
342     char *p, *buf2;
343     int i;
344     FILE *f = input;
345 
346     if (bp_save != 0) {		/* there is a partly filled input buffer left */
347 	buf_ptr = bp_save;	/* dont read anything, just switch buffers */
348 	buf_end = be_save;
349 	bp_save = be_save = 0;
350 	if (buf_ptr < buf_end)
351 	    return;		/* only return if there is really something in
352 				 * this buffer */
353     }
354     for (p = in_buffer;;) {
355 	if (p >= in_buffer_limit) {
356 	    int size = (in_buffer_limit - in_buffer) * 2 + 10;
357 	    int offset = p - in_buffer;
358 	    buf2 = realloc(in_buffer, size);
359 	    if (buf2 == NULL)
360 		errx(1, "input line too long");
361 	    in_buffer = buf2;
362 	    p = in_buffer + offset;
363 	    in_buffer_limit = in_buffer + size - 2;
364 	}
365 	if ((i = getc(f)) == EOF) {
366 		*p++ = ' ';
367 		*p++ = '\n';
368 		had_eof = true;
369 		break;
370 	}
371 	*p++ = i;
372 	if (i == '\n')
373 		break;
374     }
375     buf_ptr = in_buffer;
376     buf_end = p;
377     if (p - 3 >= in_buffer && p[-2] == '/' && p[-3] == '*') {
378 	if (in_buffer[3] == 'I' && strncmp(in_buffer, "/**INDENT**", 11) == 0)
379 	    fill_buffer();	/* flush indent error message */
380 	else {
381 	    int         com = 0;
382 
383 	    p = in_buffer;
384 	    while (*p == ' ' || *p == '\t')
385 		p++;
386 	    if (*p == '/' && p[1] == '*') {
387 		p += 2;
388 		while (*p == ' ' || *p == '\t')
389 		    p++;
390 		if (p[0] == 'I' && p[1] == 'N' && p[2] == 'D' && p[3] == 'E'
391 			&& p[4] == 'N' && p[5] == 'T') {
392 		    p += 6;
393 		    while (*p == ' ' || *p == '\t')
394 			p++;
395 		    if (*p == '*')
396 			com = 1;
397 		    else if (*p == 'O') {
398 			if (*++p == 'N')
399 			    p++, com = 1;
400 			else if (*p == 'F' && *++p == 'F')
401 			    p++, com = 2;
402 		    }
403 		    while (*p == ' ' || *p == '\t')
404 			p++;
405 		    if (p[0] == '*' && p[1] == '/' && p[2] == '\n' && com) {
406 			if (s_com != e_com || s_lab != e_lab || s_code != e_code)
407 			    dump_line();
408 			if (!(inhibit_formatting = com - 1)) {
409 			    n_real_blanklines = 0;
410 			    postfix_blankline_requested = 0;
411 			    prefix_blankline_requested = 0;
412 			    suppress_blanklines = 1;
413 			}
414 		    }
415 		}
416 	    }
417 	}
418     }
419     if (inhibit_formatting) {
420 	p = in_buffer;
421 	do
422 	    putc(*p, output);
423 	while (*p++ != '\n');
424     }
425     return;
426 }
427 
428 /*
429  * Copyright (C) 1976 by the Board of Trustees of the University of Illinois
430  *
431  * All rights reserved
432  *
433  *
434  * NAME: pad_output
435  *
436  * FUNCTION: Writes tabs and spaces to move the current column up to the desired
437  * position.
438  *
439  * ALGORITHM: Put tabs and/or blanks into pobuf, then write pobuf.
440  *
441  * PARAMETERS: current		integer		The current column target
442  *             target 		integer		The desired column
443  *
444  * RETURNS: Integer value of the new column.  (If current >= target, no action is
445  * taken, and current is returned.
446  *
447  * GLOBALS: None
448  *
449  * CALLS: write (sys)
450  *
451  * CALLED BY: dump_line
452  *
453  * HISTORY: initial coding 	November 1976	D A Willcox of CAC
454  *
455  */
456 int
pad_output(int current,int target)457 pad_output(int current, int target)
458 {
459     int curr;		/* internal column pointer */
460     int tcur;
461 
462     if (troff)
463 	fprintf(output, "\\h'|%dp'", (target - 1) * 7);
464     else {
465 	if (current >= target)
466 	    return (current);	/* line is already long enough */
467 	curr = current;
468 	while ((tcur = ((curr - 1) & tabmask) + tabsize + 1) <= target) {
469 	    putc('\t', output);
470 	    curr = tcur;
471 	}
472 	while (curr++ < target)
473 	    putc(' ', output);	/* pad with final blanks */
474     }
475     return (target);
476 }
477 
478 /*
479  * Copyright (C) 1976 by the Board of Trustees of the University of Illinois
480  *
481  * All rights reserved
482  *
483  *
484  * NAME: count_spaces
485  *
486  * FUNCTION: Find out where printing of a given string will leave the current
487  * character position on output.
488  *
489  * ALGORITHM: Run thru input string and add appropriate values to current
490  * position.
491  *
492  * RETURNS: Integer value of position after printing "buffer" starting in column
493  * "current".
494  *
495  * HISTORY: initial coding 	November 1976	D A Willcox of CAC
496  *
497  */
498 int
count_spaces(int current,char * buffer)499 count_spaces(int current, char *buffer)
500 {
501     char *buf;		/* used to look thru buffer */
502     int cur;		/* current character counter */
503 
504     cur = current;
505 
506     for (buf = buffer; *buf != '\0'; ++buf) {
507 	switch (*buf) {
508 
509 	case '\n':
510 	case 014:		/* form feed */
511 	    cur = 1;
512 	    break;
513 
514 	case '\t':
515 	    cur = ((cur - 1) & tabmask) + tabsize + 1;
516 	    break;
517 
518 	case 010:		/* backspace */
519 	    --cur;
520 	    break;
521 
522 	default:
523 	    ++cur;
524 	    break;
525 	}			/* end of switch */
526     }				/* end of for loop */
527     return (cur);
528 }
529 
530 int	found_err;
531 
532 /* VARARGS2 */
533 void
diag(int level,char * msg,...)534 diag(int level, char *msg, ...)
535 {
536     va_list ap;
537 
538     va_start(ap, msg);
539     if (level)
540 	found_err = 1;
541     if (output == stdout) {
542 	fprintf(stdout, "/**INDENT** %s@%d: ", level == 0 ? "Warning" : "Error", line_no);
543 	vfprintf(stdout, msg, ap);
544 	fprintf(stdout, " */\n");
545     }
546     else {
547 	fprintf(stderr, "%s@%d: ", level == 0 ? "Warning" : "Error", line_no);
548 	vfprintf(stderr, msg, ap);
549 	fprintf(stderr, "\n");
550     }
551     va_end(ap);
552 }
553 
554 void
writefdef(struct fstate * f,int nm)555 writefdef(struct fstate *f, int nm)
556 {
557     fprintf(output, ".ds f%c %s\n.nr s%c %d\n",
558 	    nm, f->font, nm, f->size);
559 }
560 
561 char       *
chfont(struct fstate * of,struct fstate * nf,char * s)562 chfont(struct fstate *of, struct fstate *nf, char *s)
563 {
564     if (of->font[0] != nf->font[0]
565 	    || of->font[1] != nf->font[1]) {
566 	*s++ = '\\';
567 	*s++ = 'f';
568 	if (nf->font[1]) {
569 	    *s++ = '(';
570 	    *s++ = nf->font[0];
571 	    *s++ = nf->font[1];
572 	}
573 	else
574 	    *s++ = nf->font[0];
575     }
576     if (nf->size != of->size) {
577 	*s++ = '\\';
578 	*s++ = 's';
579 	if (nf->size < of->size) {
580 	    *s++ = '-';
581 	    *s++ = '0' + of->size - nf->size;
582 	}
583 	else {
584 	    *s++ = '+';
585 	    *s++ = '0' + nf->size - of->size;
586 	}
587     }
588     return s;
589 }
590 
591 void
parsefont(struct fstate * f,char * s0)592 parsefont(struct fstate *f, char *s0)
593 {
594     char *s = s0;
595     int         sizedelta = 0;
596     bzero(f, sizeof *f);
597     while (*s) {
598 	if (isdigit(*s))
599 	    f->size = f->size * 10 + *s - '0';
600 	else if (isupper(*s))
601 	    if (f->font[0])
602 		f->font[1] = *s;
603 	    else
604 		f->font[0] = *s;
605 	else if (*s == 'c')
606 	    f->allcaps = 1;
607 	else if (*s == '+')
608 	    sizedelta++;
609 	else if (*s == '-')
610 	    sizedelta--;
611 	else
612 	    errx(1, "bad font specification: %s", s0);
613 	s++;
614     }
615     if (f->font[0] == 0)
616 	f->font[0] = 'R';
617     if (bodyf.size == 0)
618 	bodyf.size = 11;
619     if (f->size == 0)
620 	f->size = bodyf.size + sizedelta;
621     else if (sizedelta > 0)
622 	f->size += bodyf.size;
623     else
624 	f->size = bodyf.size - f->size;
625 }
626