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