lexi.c revision 1.235 1 /* $NetBSD: lexi.c,v 1.235 2023/06/25 19:29:57 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 #include <sys/cdefs.h>
41 __RCSID("$NetBSD: lexi.c,v 1.235 2023/06/25 19:29:57 rillig Exp $");
42
43 #include <stdlib.h>
44 #include <string.h>
45
46 #include "indent.h"
47
48 /* must be sorted alphabetically, is used in binary search */
49 static const struct keyword {
50 const char name[12];
51 lexer_symbol lsym;
52 } keywords[] = {
53 {"_Bool", lsym_type},
54 {"_Complex", lsym_modifier},
55 {"_Imaginary", lsym_modifier},
56 {"auto", lsym_modifier},
57 {"bool", lsym_type},
58 {"break", lsym_word},
59 {"case", lsym_case},
60 {"char", lsym_type},
61 {"complex", lsym_modifier},
62 {"const", lsym_modifier},
63 {"continue", lsym_word},
64 {"default", lsym_default},
65 {"do", lsym_do},
66 {"double", lsym_type},
67 {"else", lsym_else},
68 {"enum", lsym_tag},
69 {"extern", lsym_modifier},
70 {"float", lsym_type},
71 {"for", lsym_for},
72 {"goto", lsym_word},
73 {"if", lsym_if},
74 {"imaginary", lsym_modifier},
75 {"inline", lsym_modifier},
76 {"int", lsym_type},
77 {"long", lsym_type},
78 {"offsetof", lsym_offsetof},
79 {"register", lsym_modifier},
80 {"restrict", lsym_word},
81 {"return", lsym_return},
82 {"short", lsym_type},
83 {"signed", lsym_type},
84 {"sizeof", lsym_sizeof},
85 {"static", lsym_modifier},
86 {"struct", lsym_tag},
87 {"switch", lsym_switch},
88 {"typedef", lsym_typedef},
89 {"union", lsym_tag},
90 {"unsigned", lsym_type},
91 {"void", lsym_type},
92 {"volatile", lsym_modifier},
93 {"while", lsym_while}
94 };
95
96 static struct {
97 const char **items;
98 unsigned int len;
99 unsigned int cap;
100 } typenames;
101
102 /*-
103 * The transition table below was rewritten by hand from lx's output, given
104 * the following definitions. lx is Katherine Flavel's lexer generator.
105 *
106 * O = /[0-7]/; D = /[0-9]/; NZ = /[1-9]/;
107 * H = /[a-f0-9]/i; B = /[0-1]/; HP = /0x/i;
108 * BP = /0b/i; E = /e[+\-]?/i D+; P = /p[+\-]?/i D+;
109 * FS = /[fl]/i; IS = /u/i /(l|L|ll|LL)/? | /(l|L|ll|LL)/ /u/i?;
110 *
111 * D+ E FS? -> $float;
112 * D* "." D+ E? FS? -> $float;
113 * D+ "." E? FS? -> $float; HP H+ IS? -> $int;
114 * HP H+ P FS? -> $float; NZ D* IS? -> $int;
115 * HP H* "." H+ P FS? -> $float; "0" O* IS? -> $int;
116 * HP H+ "." P FS -> $float; BP B+ IS? -> $int;
117 */
118 /* INDENT OFF */
119 static const unsigned char lex_number_state[][26] = {
120 /* examples:
121 00
122 s 0xx
123 t 00xaa
124 a 11 101100xxa..
125 r 11ee0001101lbuuxx.a.pp
126 t.01.e+008bLuxll0Ll.aa.p+0
127 states: ABCDEFGHIJKLMNOPQRSTUVWXYZ */
128 [0] = "uuiifuufiuuiiuiiiiiuiuuuuu", /* (other) */
129 [1] = "CEIDEHHHIJQ U Q VUVVZZZ", /* 0 */
130 [2] = "DEIDEHHHIJQ U Q VUVVZZZ", /* 1 */
131 [3] = "DEIDEHHHIJ U VUVVZZZ", /* 2 3 4 5 6 7 */
132 [4] = "DEJDEHHHJJ U VUVVZZZ", /* 8 9 */
133 [5] = " U VUVV ", /* A a C c D d */
134 [6] = " K U VUVV ", /* B b */
135 [7] = " FFF FF U VUVV ", /* E e */
136 [8] = " f f U VUVV f", /* F f */
137 [9] = " LLf fL PR Li L f", /* L */
138 [10] = " OOf fO S P O i O f", /* l */
139 [11] = " FFX ", /* P p */
140 [12] = " MM M i iiM M ", /* U u */
141 [13] = " N ", /* X x */
142 [14] = " G Y ", /* + - */
143 [15] = "B EE EE T W ", /* . */
144 /* ABCDEFGHIJKLMNOPQRSTUVWXYZ */
145 };
146 /* INDENT ON */
147
148 static const unsigned char lex_number_row[] = {
149 ['0'] = 1,
150 ['1'] = 2,
151 ['2'] = 3, ['3'] = 3, ['4'] = 3, ['5'] = 3, ['6'] = 3, ['7'] = 3,
152 ['8'] = 4, ['9'] = 4,
153 ['A'] = 5, ['a'] = 5, ['C'] = 5, ['c'] = 5, ['D'] = 5, ['d'] = 5,
154 ['B'] = 6, ['b'] = 6,
155 ['E'] = 7, ['e'] = 7,
156 ['F'] = 8, ['f'] = 8,
157 ['L'] = 9,
158 ['l'] = 10,
159 ['P'] = 11, ['p'] = 11,
160 ['U'] = 12, ['u'] = 12,
161 ['X'] = 13, ['x'] = 13,
162 ['+'] = 14, ['-'] = 14,
163 ['.'] = 15,
164 };
165
166
167 static bool
168 is_identifier_start(char ch)
169 {
170 return ch_isalpha(ch) || ch == '_' || ch == '$';
171 }
172
173 static bool
174 is_identifier_part(char ch)
175 {
176 return ch_isalnum(ch) || ch == '_' || ch == '$';
177 }
178
179 static void
180 token_add_char(char ch)
181 {
182 buf_add_char(&token, ch);
183 }
184
185 static bool
186 skip_line_continuation(void)
187 {
188 if (inp_p[0] == '\\' && inp_p[1] == '\n') {
189 inp_p++;
190 inp_skip();
191 line_no++;
192 return true;
193 }
194 return false;
195 }
196
197 static void
198 lex_number(void)
199 {
200 for (unsigned char s = 'A'; s != 'f' && s != 'i' && s != 'u';) {
201 unsigned char ch = (unsigned char)*inp_p;
202 if (skip_line_continuation())
203 continue;
204 if (ch >= array_length(lex_number_row)
205 || lex_number_row[ch] == 0)
206 break;
207
208 unsigned char row = lex_number_row[ch];
209 if (lex_number_state[row][s - 'A'] == ' ') {
210 // lex_number_state[0][s - 'A'] now indicates the type:
211 // f = floating, i = integer, u = unknown
212 return;
213 }
214
215 s = lex_number_state[row][s - 'A'];
216 token_add_char(inp_next());
217 }
218 }
219
220 static void
221 lex_word(void)
222 {
223 for (;;) {
224 if (is_identifier_part(*inp_p))
225 token_add_char(*inp_p++);
226 else if (skip_line_continuation())
227 continue;
228 else
229 return;
230 }
231 }
232
233 static void
234 lex_char_or_string(void)
235 {
236 for (char delim = token.s[token.len - 1];;) {
237 if (*inp_p == '\n') {
238 diag(1, "Unterminated literal");
239 return;
240 }
241
242 token_add_char(*inp_p++);
243 if (token.s[token.len - 1] == delim)
244 return;
245
246 if (token.s[token.len - 1] == '\\') {
247 if (*inp_p == '\n')
248 line_no++;
249 token_add_char(inp_next());
250 }
251 }
252 }
253
254 /* Guess whether the current token is a declared type. */
255 static bool
256 probably_typename(void)
257 {
258 if (ps.prev_lsym == lsym_modifier)
259 return true;
260 if (ps.in_init)
261 return false;
262 if (ps.in_stmt_or_decl) /* XXX: this condition looks incorrect */
263 return false;
264 if (ps.prev_lsym == lsym_semicolon
265 || ps.prev_lsym == lsym_lbrace
266 || ps.prev_lsym == lsym_rbrace) {
267 if (inp_p[0] == '*' && inp_p[1] != '=')
268 return true;
269 /* XXX: is_identifier_start */
270 if (ch_isalpha(inp_p[0]))
271 return true;
272 }
273 return false;
274 }
275
276 static int
277 bsearch_typenames(const char *key)
278 {
279 const char **arr = typenames.items;
280 unsigned lo = 0;
281 unsigned hi = typenames.len;
282
283 while (lo < hi) {
284 unsigned mid = (lo + hi) / 2;
285 int cmp = strcmp(arr[mid], key);
286 if (cmp < 0)
287 lo = mid + 1;
288 else if (cmp > 0)
289 hi = mid;
290 else
291 return (int)mid;
292 }
293 return -1 - (int)lo;
294 }
295
296 static bool
297 is_typename(void)
298 {
299 if (opt.auto_typedefs &&
300 token.len >= 2 && memcmp(token.s + token.len - 2, "_t", 2) == 0)
301 return true;
302
303 return bsearch_typenames(token.s) >= 0;
304 }
305
306 void
307 register_typename(const char *name)
308 {
309 if (typenames.len >= typenames.cap) {
310 typenames.cap = 16 + 2 * typenames.cap;
311 typenames.items = nonnull(realloc(typenames.items,
312 sizeof(typenames.items[0]) * typenames.cap));
313 }
314
315 int pos = bsearch_typenames(name);
316 if (pos >= 0)
317 return; /* already in the list */
318
319 pos = -1 - pos;
320 memmove(typenames.items + pos + 1, typenames.items + pos,
321 sizeof(typenames.items[0]) * (typenames.len++ - (unsigned)pos));
322 typenames.items[pos] = nonnull(strdup(name));
323 }
324
325 static int
326 cmp_keyword_by_name(const void *key, const void *elem)
327 {
328 return strcmp(key, ((const struct keyword *)elem)->name);
329 }
330
331 /*
332 * Looking at the '(', guess whether this starts a function definition or a
333 * function declaration.
334 */
335 static bool
336 probably_function_definition(const char *p)
337 {
338 int paren_level = 0;
339 for (; *p != '\n'; p++) {
340 if (*p == '(')
341 paren_level++;
342 if (*p == ')' && --paren_level == 0) {
343 p++;
344
345 while (*p != '\n'
346 && (ch_isspace(*p) || is_identifier_part(*p)))
347 p++; /* '__dead' or '__unused' */
348
349 if (*p == '\n') /* func(...) */
350 break;
351 if (*p == ';') /* func(...); */
352 return false;
353 if (*p == ',') /* double abs(), pi; */
354 return false;
355 if (*p == '(') /* func(...) __attribute__((...)) */
356 paren_level++; /* func(...) __printflike(...)
357 */
358 else
359 break; /* func(...) { ... */
360 }
361
362 if (paren_level == 1 && p[0] == '*' && p[1] == ',')
363 return false;
364 }
365
366 /*
367 * To further reduce the cases where indent wrongly treats an
368 * incomplete function declaration as a function definition, thus
369 * adding a newline before the function name, it may be worth looking
370 * for parameter names, as these are often omitted in function
371 * declarations and only included in function definitions. Or just
372 * increase the lookahead to more than just the current line of input,
373 * until the next '{'.
374 */
375 return true;
376 }
377
378 static lexer_symbol
379 lexi_alnum(void)
380 {
381 if (ch_isdigit(inp_p[0]) ||
382 (inp_p[0] == '.' && ch_isdigit(inp_p[1]))) {
383 lex_number();
384 } else if (is_identifier_start(inp_p[0])) {
385 lex_word();
386
387 if (token.len == 1 && token.s[0] == 'L' &&
388 (inp_p[0] == '"' || inp_p[0] == '\'')) {
389 token_add_char(*inp_p++);
390 lex_char_or_string();
391 ps.next_unary = false;
392 return lsym_word;
393 }
394 } else
395 return lsym_eof; /* just as a placeholder */
396
397 while (ch_isblank(*inp_p))
398 inp_p++;
399
400 ps.next_unary = ps.prev_lsym == lsym_tag
401 || ps.prev_lsym == lsym_typedef;
402
403 if (ps.prev_lsym == lsym_tag && ps.paren.len == 0)
404 return lsym_type;
405
406 token_add_char('\0'); // Terminate in non-debug mode as well.
407 token.len--;
408 const struct keyword *kw = bsearch(token.s, keywords,
409 array_length(keywords), sizeof(keywords[0]), cmp_keyword_by_name);
410 lexer_symbol lsym = lsym_word;
411 if (kw != NULL) {
412 if (kw->lsym == lsym_type)
413 lsym = lsym_type;
414 ps.next_unary = true;
415 if (kw->lsym == lsym_tag || kw->lsym == lsym_type)
416 goto found_typename;
417 return kw->lsym;
418 }
419
420 if (is_typename()) {
421 lsym = lsym_type;
422 ps.next_unary = true;
423 found_typename:
424 if (ps.paren.len > 0) {
425 /* inside parentheses: cast, param list, offsetof or
426 * sizeof */
427 struct paren_level *paren_level =
428 ps.paren.item + ps.paren.len - 1;
429 if (paren_level->cast == cast_unknown)
430 paren_level->cast = cast_maybe;
431 }
432 if (ps.prev_lsym != lsym_period
433 && ps.prev_lsym != lsym_unary_op) {
434 if (kw != NULL && kw->lsym == lsym_tag)
435 return lsym_tag;
436 if (ps.paren.len == 0)
437 return lsym_type;
438 }
439 }
440
441 const char *p = inp_p;
442 if (*p == ')')
443 p++;
444 if (*p == '(' && ps.psyms.len < 3 && ps.ind_level == 0 &&
445 !ps.in_func_def_params && !ps.in_init) {
446
447 bool maybe_function_definition = *inp_p == ')'
448 ? ps.paren.len == 1 && ps.prev_lsym != lsym_unary_op
449 : ps.paren.len == 0;
450 if (maybe_function_definition
451 && probably_function_definition(p)) {
452 ps.line_has_func_def = true;
453 if (ps.in_decl)
454 ps.in_func_def_params = true;
455 return lsym_funcname;
456 }
457
458 } else if (ps.paren.len == 0 && probably_typename()) {
459 ps.next_unary = true;
460 return lsym_type;
461 }
462
463 return lsym;
464 }
465
466 static void
467 check_parenthesized_function_definition(void)
468 {
469 const char *p = inp_p;
470 while (ch_isblank(*p))
471 p++;
472 if (is_identifier_start(*p))
473 while (is_identifier_part(*p))
474 p++;
475 while (ch_isblank(*p))
476 p++;
477 if (*p == ')') {
478 p++;
479 while (ch_isblank(*p))
480 p++;
481 if (*p == '(' && probably_function_definition(p))
482 ps.line_has_func_def = true;
483 }
484 }
485
486 static bool
487 is_asterisk_unary(void)
488 {
489 const char *p = inp_p;
490 while (*p == '*' || ch_isblank(*p))
491 p++;
492 if (*p == ')')
493 return true;
494 if (ps.next_unary || ps.in_func_def_params)
495 return true;
496 if (ps.prev_lsym == lsym_word ||
497 ps.prev_lsym == lsym_rparen ||
498 ps.prev_lsym == lsym_rbracket)
499 return false;
500 return ps.in_decl && ps.paren.len > 0;
501 }
502
503 static bool
504 probably_in_function_definition(void)
505 {
506 for (const char *p = inp_p; *p != '\n';) {
507 if (ch_isspace(*p))
508 p++;
509 else if (is_identifier_start(*p)) {
510 p++;
511 while (is_identifier_part(*p))
512 p++;
513 } else
514 return *p == '(';
515 }
516 return false;
517 }
518
519 static void
520 lex_asterisk_unary(void)
521 {
522 while (*inp_p == '*' || ch_isspace(*inp_p)) {
523 if (*inp_p == '*')
524 token_add_char('*');
525 inp_skip();
526 }
527
528 if (ps.in_decl && probably_in_function_definition())
529 ps.line_has_func_def = true;
530 }
531
532 static bool
533 skip(const char **pp, const char *s)
534 {
535 size_t len = strlen(s);
536 while (ch_isblank(**pp))
537 (*pp)++;
538 if (strncmp(*pp, s, len) == 0) {
539 *pp += len;
540 return true;
541 }
542 return false;
543 }
544
545 static void
546 lex_indent_comment(void)
547 {
548 const char *p = inp.s;
549 if (skip(&p, "/*") && skip(&p, "INDENT")) {
550 enum indent_enabled enabled;
551 if (skip(&p, "ON") || *p == '*')
552 enabled = indent_last_off_line;
553 else if (skip(&p, "OFF"))
554 enabled = indent_off;
555 else
556 return;
557 if (skip(&p, "*/\n")) {
558 if (lab.len > 0 || code.len > 0 || com.len > 0)
559 output_line();
560 indent_enabled = enabled;
561 }
562 }
563 }
564
565 /* Reads the next token, placing it in the global variable "token". */
566 lexer_symbol
567 lexi(void)
568 {
569 buf_clear(&token);
570
571 for (;;) {
572 if (ch_isblank(*inp_p))
573 inp_p++;
574 else if (skip_line_continuation())
575 continue;
576 else
577 break;
578 }
579
580 lexer_symbol alnum_lsym = lexi_alnum();
581 if (alnum_lsym != lsym_eof)
582 return alnum_lsym;
583
584 /* Scan a non-alphanumeric token */
585
586 token_add_char(inp_next());
587
588 lexer_symbol lsym;
589 bool next_unary;
590
591 switch (token.s[token.len - 1]) {
592
593 case '#':
594 lsym = lsym_preprocessing;
595 next_unary = ps.next_unary;
596 break;
597
598 case '\n':
599 /* if data has been exhausted, the '\n' is a dummy. */
600 lsym = had_eof ? lsym_eof : lsym_newline;
601 next_unary = ps.next_unary;
602 break;
603
604 /* INDENT OFF */
605 case ')': lsym = lsym_rparen; next_unary = false; break;
606 case '[': lsym = lsym_lbracket; next_unary = true; break;
607 case ']': lsym = lsym_rbracket; next_unary = false; break;
608 case '{': lsym = lsym_lbrace; next_unary = true; break;
609 case '}': lsym = lsym_rbrace; next_unary = true; break;
610 case '.': lsym = lsym_period; next_unary = false; break;
611 case '?': lsym = lsym_question; next_unary = true; break;
612 case ',': lsym = lsym_comma; next_unary = true; break;
613 case ';': lsym = lsym_semicolon; next_unary = true; break;
614 /* INDENT ON */
615
616 case '(':
617 if (inp_p == inp.s + 1)
618 check_parenthesized_function_definition();
619 lsym = lsym_lparen;
620 next_unary = true;
621 break;
622
623 case '+':
624 case '-':
625 lsym = ps.next_unary ? lsym_unary_op : lsym_binary_op;
626 next_unary = true;
627
628 /* '++' or '--' */
629 if (*inp_p == token.s[token.len - 1]) {
630 token_add_char(*inp_p++);
631 if (ps.prev_lsym == lsym_word ||
632 ps.prev_lsym == lsym_rparen ||
633 ps.prev_lsym == lsym_rbracket) {
634 lsym = ps.next_unary
635 ? lsym_unary_op : lsym_postfix_op;
636 next_unary = false;
637 }
638
639 } else if (*inp_p == '=') { /* '+=' or '-=' */
640 token_add_char(*inp_p++);
641
642 } else if (*inp_p == '>') { /* '->' */
643 token_add_char(*inp_p++);
644 lsym = lsym_unary_op;
645 next_unary = false;
646 ps.want_blank = false;
647 }
648 break;
649
650 case ':':
651 lsym = ps.quest_level > 0
652 ? (ps.quest_level--, lsym_question_colon)
653 : ps.in_var_decl ? lsym_other_colon : lsym_label_colon;
654 next_unary = true;
655 break;
656
657 case '*':
658 if (*inp_p == '=') {
659 token_add_char(*inp_p++);
660 lsym = lsym_binary_op;
661 } else if (is_asterisk_unary()) {
662 lex_asterisk_unary();
663 lsym = lsym_unary_op;
664 } else
665 lsym = lsym_binary_op;
666 next_unary = true;
667 break;
668
669 case '=':
670 if (ps.in_var_decl)
671 ps.in_init = true;
672 if (*inp_p == '=')
673 token_add_char(*inp_p++);
674 lsym = lsym_binary_op;
675 next_unary = true;
676 break;
677
678 case '>':
679 case '<':
680 case '!': /* ops like <, <<, <=, !=, etc. */
681 if (*inp_p == '>' || *inp_p == '<' || *inp_p == '=')
682 token_add_char(*inp_p++);
683 if (*inp_p == '=')
684 token_add_char(*inp_p++);
685 lsym = ps.next_unary ? lsym_unary_op : lsym_binary_op;
686 next_unary = true;
687 break;
688
689 case '\'':
690 case '"':
691 lex_char_or_string();
692 lsym = lsym_word;
693 next_unary = false;
694 break;
695
696 default:
697 if (token.s[token.len - 1] == '/'
698 && (*inp_p == '*' || *inp_p == '/')) {
699 enum indent_enabled prev = indent_enabled;
700 lex_indent_comment();
701 if (prev == indent_on && indent_enabled == indent_off)
702 buf_clear(&out.indent_off_text);
703 token_add_char(*inp_p++);
704 lsym = lsym_comment;
705 next_unary = ps.next_unary;
706 break;
707 }
708
709 /* punctuation like '%', '&&', '/', '^', '||', '~' */
710 lsym = ps.next_unary ? lsym_unary_op : lsym_binary_op;
711 if (*inp_p == token.s[token.len - 1])
712 token_add_char(*inp_p++), lsym = lsym_binary_op;
713 if (*inp_p == '=')
714 token_add_char(*inp_p++), lsym = lsym_binary_op;
715
716 next_unary = true;
717 }
718
719 ps.next_unary = next_unary;
720
721 return lsym;
722 }
723