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