lexi.c revision 1.87 1 /* $NetBSD: lexi.c,v 1.87 2021/10/08 23:55:44 rillig Exp $ */
2
3 /*-
4 * SPDX-License-Identifier: BSD-4-Clause
5 *
6 * Copyright (c) 1985 Sun Microsystems, Inc.
7 * Copyright (c) 1980, 1993
8 * The Regents of the University of California. All rights reserved.
9 * 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[] = "@(#)lexi.c 8.1 (Berkeley) 6/6/93";
42 #endif
43
44 #include <sys/cdefs.h>
45 #if defined(__NetBSD__)
46 __RCSID("$NetBSD: lexi.c,v 1.87 2021/10/08 23:55:44 rillig Exp $");
47 #elif defined(__FreeBSD__)
48 __FBSDID("$FreeBSD: head/usr.bin/indent/lexi.c 337862 2018-08-15 18:19:45Z pstef $");
49 #endif
50
51 #include <assert.h>
52 #include <stdio.h>
53 #include <ctype.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <sys/param.h>
57
58 #include "indent.h"
59
60 /* must be sorted alphabetically, is used in binary search */
61 static const struct keyword {
62 const char *name;
63 enum keyword_kind kind;
64 } keywords[] = {
65 {"_Bool", kw_type},
66 {"_Complex", kw_type},
67 {"_Imaginary", kw_type},
68 {"auto", kw_storage_class},
69 {"bool", kw_type},
70 {"break", kw_jump},
71 {"case", kw_case_or_default},
72 {"char", kw_type},
73 {"complex", kw_type},
74 {"const", kw_type},
75 {"continue", kw_jump},
76 {"default", kw_case_or_default},
77 {"do", kw_do_or_else},
78 {"double", kw_type},
79 {"else", kw_do_or_else},
80 {"enum", kw_struct_or_union_or_enum},
81 {"extern", kw_storage_class},
82 {"float", kw_type},
83 {"for", kw_for_or_if_or_while},
84 {"goto", kw_jump},
85 {"if", kw_for_or_if_or_while},
86 {"imaginary", kw_type},
87 {"inline", kw_inline_or_restrict},
88 {"int", kw_type},
89 {"long", kw_type},
90 {"offsetof", kw_offsetof},
91 {"register", kw_storage_class},
92 {"restrict", kw_inline_or_restrict},
93 {"return", kw_jump},
94 {"short", kw_type},
95 {"signed", kw_type},
96 {"sizeof", kw_sizeof},
97 {"static", kw_storage_class},
98 {"struct", kw_struct_or_union_or_enum},
99 {"switch", kw_switch},
100 {"typedef", kw_typedef},
101 {"union", kw_struct_or_union_or_enum},
102 {"unsigned", kw_type},
103 {"void", kw_type},
104 {"volatile", kw_type},
105 {"while", kw_for_or_if_or_while}
106 };
107
108 static struct {
109 const char **items;
110 unsigned int len;
111 unsigned int cap;
112 } typenames;
113
114 /*
115 * The transition table below was rewritten by hand from lx's output, given
116 * the following definitions. lx is Katherine Flavel's lexer generator.
117 *
118 * O = /[0-7]/; D = /[0-9]/; NZ = /[1-9]/;
119 * H = /[a-f0-9]/i; B = /[0-1]/; HP = /0x/i;
120 * BP = /0b/i; E = /e[+\-]?/i D+; P = /p[+\-]?/i D+;
121 * FS = /[fl]/i; IS = /u/i /(l|L|ll|LL)/? | /(l|L|ll|LL)/ /u/i?;
122 *
123 * D+ E FS? -> $float;
124 * D* "." D+ E? FS? -> $float;
125 * D+ "." E? FS? -> $float; HP H+ IS? -> $int;
126 * HP H+ P FS? -> $float; NZ D* IS? -> $int;
127 * HP H* "." H+ P FS? -> $float; "0" O* IS? -> $int;
128 * HP H+ "." P FS -> $float; BP B+ IS? -> $int;
129 */
130 /* INDENT OFF */
131 static const unsigned char lex_number_state[][26] = {
132 /* examples:
133 00
134 s 0xx
135 t 00xaa
136 a 11 101100xxa..
137 r 11ee0001101lbuuxx.a.pp
138 t.01.e+008bLuxll0Ll.aa.p+0
139 states: ABCDEFGHIJKLMNOPQRSTUVWXYZ */
140 [0] = "uuiifuufiuuiiuiiiiiuiuuuuu", /* (other) */
141 [1] = "CEIDEHHHIJQ U Q VUVVZZZ", /* 0 */
142 [2] = "DEIDEHHHIJQ U Q VUVVZZZ", /* 1 */
143 [3] = "DEIDEHHHIJ U VUVVZZZ", /* 2 3 4 5 6 7 */
144 [4] = "DEJDEHHHJJ U VUVVZZZ", /* 8 9 */
145 [5] = " U VUVV ", /* A a C c D d */
146 [6] = " K U VUVV ", /* B b */
147 [7] = " FFF FF U VUVV ", /* E e */
148 [8] = " f f U VUVV f", /* F f */
149 [9] = " LLf fL PR Li L f", /* L */
150 [10] = " OOf fO S P O i O f", /* l */
151 [11] = " FFX ", /* P p */
152 [12] = " MM M i iiM M ", /* U u */
153 [13] = " N ", /* X x */
154 [14] = " G Y ", /* + - */
155 [15] = "B EE EE T W ", /* . */
156 /* ABCDEFGHIJKLMNOPQRSTUVWXYZ */
157 };
158 /* INDENT ON */
159
160 static const uint8_t lex_number_row[] = {
161 ['0'] = 1,
162 ['1'] = 2,
163 ['2'] = 3, ['3'] = 3, ['4'] = 3, ['5'] = 3, ['6'] = 3, ['7'] = 3,
164 ['8'] = 4, ['9'] = 4,
165 ['A'] = 5, ['a'] = 5, ['C'] = 5, ['c'] = 5, ['D'] = 5, ['d'] = 5,
166 ['B'] = 6, ['b'] = 6,
167 ['E'] = 7, ['e'] = 7,
168 ['F'] = 8, ['f'] = 8,
169 ['L'] = 9,
170 ['l'] = 10,
171 ['P'] = 11, ['p'] = 11,
172 ['U'] = 12, ['u'] = 12,
173 ['X'] = 13, ['x'] = 13,
174 ['+'] = 14, ['-'] = 14,
175 ['.'] = 15,
176 };
177
178 static char
179 inbuf_peek(void)
180 {
181 return *inp.s;
182 }
183
184 void
185 inbuf_skip(void)
186 {
187 inp.s++;
188 if (inp.s >= inp.e)
189 inbuf_read_line();
190 }
191
192 char
193 inbuf_next(void)
194 {
195 char ch = inbuf_peek();
196 inbuf_skip();
197 return ch;
198 }
199
200 static void
201 check_size_token(size_t desired_size)
202 {
203 if (token.e + desired_size >= token.l)
204 buf_expand(&token, desired_size);
205 }
206
207 static void
208 token_add_char(char ch)
209 {
210 check_size_token(1);
211 *token.e++ = ch;
212 }
213
214 static int
215 cmp_keyword_by_name(const void *key, const void *elem)
216 {
217 return strcmp(key, ((const struct keyword *)elem)->name);
218 }
219
220 #ifdef debug
221 const char *
222 token_type_name(token_type ttype)
223 {
224 static const char *const name[] = {
225 "end_of_file", "newline", "lparen_or_lbracket", "rparen_or_rbracket",
226 "unary_op", "binary_op", "postfix_op", "question",
227 "case_label", "colon",
228 "semicolon", "lbrace", "rbrace", "ident", "comma",
229 "comment", "switch_expr", "preprocessing", "form_feed", "decl",
230 "keyword_for_if_while", "keyword_do_else",
231 "if_expr", "while_expr", "for_exprs",
232 "stmt", "stmt_list", "keyword_else", "keyword_do", "do_stmt",
233 "if_expr_stmt", "if_expr_stmt_else", "period", "string_prefix",
234 "storage_class", "funcname", "type_def", "keyword_struct_union_enum"
235 };
236
237 assert(0 <= ttype && ttype < nitems(name));
238
239 return name[ttype];
240 }
241
242 static void
243 debug_print_buf(const char *name, const struct buffer *buf)
244 {
245 if (buf->s < buf->e) {
246 debug_printf(" %s ", name);
247 debug_vis_range("\"", buf->s, buf->e, "\"");
248 }
249 }
250
251 static token_type
252 lexi_end(token_type ttype)
253 {
254 debug_printf("in line %d, lexi returns '%s'",
255 line_no, token_type_name(ttype));
256 debug_print_buf("token", &token);
257 debug_print_buf("label", &lab);
258 debug_print_buf("code", &code);
259 debug_print_buf("comment", &com);
260 debug_printf("\n");
261
262 return ttype;
263 }
264 #else
265 #define lexi_end(tk) (tk)
266 #endif
267
268 static void
269 lex_number(void)
270 {
271 for (uint8_t s = 'A'; s != 'f' && s != 'i' && s != 'u';) {
272 uint8_t ch = (uint8_t)*inp.s;
273 if (ch >= nitems(lex_number_row) || lex_number_row[ch] == 0)
274 break;
275
276 uint8_t row = lex_number_row[ch];
277 if (lex_number_state[row][s - 'A'] == ' ') {
278 /*-
279 * lex_number_state[0][s - 'A'] now indicates the type:
280 * f = floating, i = integer, u = unknown
281 */
282 break;
283 }
284
285 s = lex_number_state[row][s - 'A'];
286 token_add_char(inbuf_next());
287 }
288 }
289
290 static void
291 lex_word(void)
292 {
293 while (isalnum((unsigned char)*inp.s) ||
294 *inp.s == '\\' ||
295 *inp.s == '_' || *inp.s == '$') {
296
297 if (*inp.s == '\\') {
298 if (inp.s[1] == '\n') {
299 inp.s += 2;
300 if (inp.s >= inp.e)
301 inbuf_read_line();
302 } else
303 break;
304 }
305
306 token_add_char(inbuf_next());
307 }
308 }
309
310 static void
311 lex_char_or_string(void)
312 {
313 for (char delim = *token.s;;) {
314 if (*inp.s == '\n') {
315 diag(1, "Unterminated literal");
316 return;
317 }
318
319 token_add_char(inbuf_next());
320 if (token.e[-1] == delim)
321 return;
322
323 if (token.e[-1] == '\\') {
324 if (*inp.s == '\n')
325 ++line_no;
326 token_add_char(inbuf_next());
327 }
328 }
329 }
330
331 /* Guess whether the current token is a declared type. */
332 static bool
333 probably_typename(const struct parser_state *state)
334 {
335 if (state->p_l_follow != 0)
336 return false;
337 if (state->block_init || state->in_stmt)
338 return false;
339 if (inp.s[0] == '*' && inp.s[1] != '=')
340 goto maybe;
341 if (isalpha((unsigned char)*inp.s))
342 goto maybe;
343 return false;
344 maybe:
345 return state->last_token == semicolon ||
346 state->last_token == lbrace ||
347 state->last_token == rbrace;
348 }
349
350 static int
351 bsearch_typenames(const char *key)
352 {
353 const char **arr = typenames.items;
354 int lo = 0;
355 int hi = (int)typenames.len - 1;
356
357 while (lo <= hi) {
358 int mid = (int)((unsigned)(lo + hi) >> 1);
359 int cmp = strcmp(arr[mid], key);
360 if (cmp < 0)
361 lo = mid + 1;
362 else if (cmp > 0)
363 hi = mid - 1;
364 else
365 return mid;
366 }
367 return -(lo + 1);
368 }
369
370 static bool
371 is_typename(void)
372 {
373 if (opt.auto_typedefs &&
374 token.e - token.s >= 2 && memcmp(token.e - 2, "_t", 2) == 0)
375 return true;
376
377 return bsearch_typenames(token.s) >= 0;
378 }
379
380 /* Reads the next token, placing it in the global variable "token". */
381 token_type
382 lexi(struct parser_state *state)
383 {
384 bool unary_delim; /* whether the current token forces a
385 * following operator to be unary */
386 token_type ttype;
387
388 token.e = token.s; /* point to start of place to save token */
389 unary_delim = false;
390 state->col_1 = state->last_nl; /* tell world that this token started
391 * in column 1 iff the last thing
392 * scanned was a newline */
393 state->last_nl = false;
394
395 while (is_hspace(*inp.s)) {
396 state->col_1 = false;
397 inbuf_skip();
398 }
399
400 /* Scan an alphanumeric token */
401 if (isalnum((unsigned char)*inp.s) ||
402 *inp.s == '_' || *inp.s == '$' ||
403 (inp.s[0] == '.' && isdigit((unsigned char)inp.s[1]))) {
404 struct keyword *kw;
405
406 if (isdigit((unsigned char)*inp.s) ||
407 (inp.s[0] == '.' && isdigit((unsigned char)inp.s[1]))) {
408 lex_number();
409 } else {
410 lex_word();
411 }
412 *token.e = '\0';
413
414 if (token.s[0] == 'L' && token.s[1] == '\0' &&
415 (*inp.s == '"' || *inp.s == '\''))
416 return lexi_end(string_prefix);
417
418 while (is_hspace(inbuf_peek()))
419 inbuf_skip();
420 state->keyword = kw_0;
421
422 if (state->last_token == keyword_struct_union_enum &&
423 state->p_l_follow == 0) {
424 state->last_u_d = true;
425 return lexi_end(decl);
426 }
427 /*
428 * Operator after identifier is binary unless last token was 'struct'
429 */
430 state->last_u_d = (state->last_token == keyword_struct_union_enum);
431
432 kw = bsearch(token.s, keywords, nitems(keywords),
433 sizeof(keywords[0]), cmp_keyword_by_name);
434 if (kw == NULL) {
435 if (is_typename()) {
436 state->keyword = kw_type;
437 state->last_u_d = true;
438 goto found_typename;
439 }
440
441 } else { /* we have a keyword */
442 state->keyword = kw->kind;
443 state->last_u_d = true;
444
445 switch (kw->kind) {
446 case kw_switch:
447 return lexi_end(switch_expr);
448
449 case kw_case_or_default:
450 return lexi_end(case_label);
451
452 case kw_struct_or_union_or_enum:
453 case kw_type:
454 found_typename:
455 if (state->p_l_follow != 0) {
456 /* inside parens: cast, param list, offsetof or sizeof */
457 state->cast_mask |= (1 << state->p_l_follow) & ~state->not_cast_mask;
458 }
459 if (state->last_token == period || state->last_token == unary_op) {
460 state->keyword = kw_0;
461 break;
462 }
463 if (kw != NULL && kw->kind == kw_struct_or_union_or_enum)
464 return lexi_end(keyword_struct_union_enum);
465 if (state->p_l_follow != 0)
466 break;
467 return lexi_end(decl);
468
469 case kw_for_or_if_or_while:
470 return lexi_end(keyword_for_if_while);
471
472 case kw_do_or_else:
473 return lexi_end(keyword_do_else);
474
475 case kw_storage_class:
476 return lexi_end(storage_class);
477
478 case kw_typedef:
479 return lexi_end(type_def);
480
481 default: /* all others are treated like any other
482 * identifier */
483 return lexi_end(ident);
484 } /* end of switch */
485 } /* end of if (found_it) */
486
487 if (*inp.s == '(' && state->tos <= 1 && state->ind_level == 0 &&
488 !state->in_parameter_declaration && !state->block_init) {
489
490 for (const char *p = inp.s; p < inp.e;)
491 if (*p++ == ')' && (*p == ';' || *p == ','))
492 goto not_proc;
493
494 strncpy(state->procname, token.s, sizeof state->procname - 1);
495 if (state->in_decl)
496 state->in_parameter_declaration = true;
497 return lexi_end(funcname);
498 not_proc:;
499
500 } else if (probably_typename(state)) {
501 state->keyword = kw_type;
502 state->last_u_d = true;
503 return lexi_end(decl);
504 }
505
506 if (state->last_token == decl) /* if this is a declared variable,
507 * then following sign is unary */
508 state->last_u_d = true; /* will make "int a -1" work */
509
510 return lexi_end(ident); /* the ident is not in the list */
511 } /* end of processing for alphanum character */
512
513 /* Scan a non-alphanumeric token */
514
515 check_size_token(3); /* things like "<<=" */
516 *token.e++ = inbuf_next(); /* if it is only a one-character token, it is
517 * moved here */
518 *token.e = '\0';
519
520 switch (*token.s) {
521 case '\n':
522 unary_delim = state->last_u_d;
523 state->last_nl = true; /* remember that we just had a newline */
524 /* if data has been exhausted, the newline is a dummy. */
525 ttype = had_eof ? end_of_file : newline;
526 break;
527
528 case '\'':
529 case '"':
530 lex_char_or_string();
531 ttype = ident;
532 break;
533
534 case '(':
535 case '[':
536 unary_delim = true;
537 ttype = lparen_or_lbracket;
538 break;
539
540 case ')':
541 case ']':
542 ttype = rparen_or_rbracket;
543 break;
544
545 case '#':
546 unary_delim = state->last_u_d;
547 ttype = preprocessing;
548 break;
549
550 case '?':
551 unary_delim = true;
552 ttype = question;
553 break;
554
555 case ':':
556 ttype = colon;
557 unary_delim = true;
558 break;
559
560 case ';':
561 unary_delim = true;
562 ttype = semicolon;
563 break;
564
565 case '{':
566 unary_delim = true;
567 ttype = lbrace;
568 break;
569
570 case '}':
571 unary_delim = true;
572 ttype = rbrace;
573 break;
574
575 case '\f':
576 unary_delim = state->last_u_d;
577 state->last_nl = true; /* remember this, so we can set 'state->col_1'
578 * right */
579 ttype = form_feed;
580 break;
581
582 case ',':
583 unary_delim = true;
584 ttype = comma;
585 break;
586
587 case '.':
588 unary_delim = false;
589 ttype = period;
590 break;
591
592 case '-':
593 case '+': /* check for -, +, --, ++ */
594 ttype = state->last_u_d ? unary_op : binary_op;
595 unary_delim = true;
596
597 if (*inp.s == token.s[0]) {
598 /* check for doubled character */
599 *token.e++ = *inp.s++;
600 /* buffer overflow will be checked at end of loop */
601 if (state->last_token == ident ||
602 state->last_token == rparen_or_rbracket) {
603 ttype = state->last_u_d ? unary_op : postfix_op;
604 /* check for following ++ or -- */
605 unary_delim = false;
606 }
607
608 } else if (*inp.s == '=') {
609 /* check for operator += */
610 *token.e++ = *inp.s++;
611
612 } else if (*inp.s == '>') {
613 /* check for operator -> */
614 *token.e++ = *inp.s++;
615 unary_delim = false;
616 ttype = unary_op;
617 state->want_blank = false;
618 }
619 break; /* buffer overflow will be checked at end of
620 * switch */
621
622 case '=':
623 if (state->init_or_struct)
624 state->block_init = true;
625 if (*inp.s == '=') { /* == */
626 *token.e++ = *inp.s++;
627 *token.e = '\0';
628 }
629 ttype = binary_op;
630 unary_delim = true;
631 break;
632
633 case '>':
634 case '<':
635 case '!': /* ops like <, <<, <=, !=, etc */
636 if (*inp.s == '>' || *inp.s == '<' || *inp.s == '=')
637 *token.e++ = inbuf_next();
638 if (*inp.s == '=')
639 *token.e++ = *inp.s++;
640 ttype = state->last_u_d ? unary_op : binary_op;
641 unary_delim = true;
642 break;
643
644 case '*':
645 unary_delim = true;
646 if (!state->last_u_d) {
647 if (*inp.s == '=')
648 *token.e++ = *inp.s++;
649 ttype = binary_op;
650 break;
651 }
652
653 while (*inp.s == '*' || isspace((unsigned char)*inp.s)) {
654 if (*inp.s == '*')
655 token_add_char('*');
656 inbuf_skip();
657 }
658
659 if (ps.in_decl) {
660 char *tp = inp.s;
661
662 while (isalpha((unsigned char)*tp) ||
663 isspace((unsigned char)*tp)) {
664 if (++tp >= inp.e)
665 inbuf_read_line();
666 }
667 if (*tp == '(')
668 ps.procname[0] = ' ';
669 }
670
671 ttype = unary_op;
672 break;
673
674 default:
675 if (token.s[0] == '/' && (*inp.s == '*' || *inp.s == '/')) {
676 /* it is start of comment */
677 *token.e++ = inbuf_next();
678
679 ttype = comment;
680 unary_delim = state->last_u_d;
681 break;
682 }
683
684 while (token.e[-1] == *inp.s || *inp.s == '=') {
685 /* handle '||', '&&', etc., and also things as in 'int *****i' */
686 token_add_char(inbuf_next());
687 }
688
689 ttype = state->last_u_d ? unary_op : binary_op;
690 unary_delim = true;
691 }
692
693 if (inp.s >= inp.e) /* check for input buffer empty */
694 inbuf_read_line();
695
696 state->last_u_d = unary_delim;
697
698 check_size_token(1);
699 *token.e = '\0';
700
701 return lexi_end(ttype);
702 }
703
704 void
705 add_typename(const char *name)
706 {
707 if (typenames.len >= typenames.cap) {
708 typenames.cap = 16 + 2 * typenames.cap;
709 typenames.items = xrealloc(typenames.items,
710 sizeof(typenames.items[0]) * typenames.cap);
711 }
712
713 int pos = bsearch_typenames(name);
714 if (pos >= 0)
715 return; /* already in the list */
716
717 pos = -(pos + 1);
718 memmove(typenames.items + pos + 1, typenames.items + pos,
719 sizeof(typenames.items[0]) * (typenames.len++ - (unsigned)pos));
720 typenames.items[pos] = xstrdup(name);
721 }
722