lexi.c revision 1.233 1 /* $NetBSD: lexi.c,v 1.233 2023/06/25 18:41:03 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.233 2023/06/25 18:41:03 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_type},
55 {"_Imaginary", lsym_type},
56 {"auto", lsym_modifier},
57 {"bool", lsym_type},
58 {"break", lsym_word},
59 {"case", lsym_case},
60 {"char", lsym_type},
61 {"complex", lsym_type},
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_type},
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(void)
337 {
338 int paren_level = 0;
339 for (const char *p = inp_p; *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 if (*inp_p == '(' && ps.psyms.len < 3 && ps.ind_level == 0 &&
442 !ps.in_func_def_params && !ps.in_init) {
443
444 if (ps.paren.len == 0 && probably_function_definition()) {
445 ps.line_has_func_def = true;
446 if (ps.in_decl)
447 ps.in_func_def_params = true;
448 return lsym_funcname;
449 }
450
451 } else if (ps.paren.len == 0 && probably_typename()) {
452 ps.next_unary = true;
453 return lsym_type;
454 }
455
456 return lsym;
457 }
458
459 static bool
460 is_asterisk_pointer(void)
461 {
462 const char *p = inp_p;
463 while (*p == '*' || ch_isblank(*p))
464 p++;
465 if (*p == ')')
466 return true;
467 if (ps.next_unary || ps.in_func_def_params)
468 return true;
469 if (ps.prev_lsym == lsym_word ||
470 ps.prev_lsym == lsym_rparen ||
471 ps.prev_lsym == lsym_rbracket)
472 return false;
473 return ps.in_decl && ps.paren.len > 0;
474 }
475
476 static bool
477 probably_in_function_definition(void)
478 {
479 for (const char *p = inp_p; *p != '\n';) {
480 if (ch_isspace(*p))
481 p++;
482 else if (is_identifier_start(*p)) {
483 p++;
484 while (is_identifier_part(*p))
485 p++;
486 } else
487 return *p == '(';
488 }
489 return false;
490 }
491
492 static void
493 lex_asterisk_pointer(void)
494 {
495 while (*inp_p == '*' || ch_isspace(*inp_p)) {
496 if (*inp_p == '*')
497 token_add_char('*');
498 inp_skip();
499 }
500
501 if (ps.in_decl && probably_in_function_definition())
502 ps.line_has_func_def = true;
503 }
504
505 static bool
506 skip(const char **pp, const char *s)
507 {
508 size_t len = strlen(s);
509 while (ch_isblank(**pp))
510 (*pp)++;
511 if (strncmp(*pp, s, len) == 0) {
512 *pp += len;
513 return true;
514 }
515 return false;
516 }
517
518 static void
519 lex_indent_comment(void)
520 {
521 const char *p = inp.s;
522 if (skip(&p, "/*") && skip(&p, "INDENT")) {
523 enum indent_enabled enabled;
524 if (skip(&p, "ON") || *p == '*')
525 enabled = indent_last_off_line;
526 else if (skip(&p, "OFF"))
527 enabled = indent_off;
528 else
529 return;
530 if (skip(&p, "*/\n")) {
531 if (lab.len > 0 || code.len > 0 || com.len > 0)
532 output_line();
533 indent_enabled = enabled;
534 }
535 }
536 }
537
538 /* Reads the next token, placing it in the global variable "token". */
539 lexer_symbol
540 lexi(void)
541 {
542 buf_clear(&token);
543
544 for (;;) {
545 if (ch_isblank(*inp_p))
546 inp_p++;
547 else if (skip_line_continuation())
548 continue;
549 else
550 break;
551 }
552
553 lexer_symbol alnum_lsym = lexi_alnum();
554 if (alnum_lsym != lsym_eof)
555 return alnum_lsym;
556
557 /* Scan a non-alphanumeric token */
558
559 token_add_char(inp_next());
560
561 lexer_symbol lsym;
562 bool next_unary;
563
564 switch (token.s[token.len - 1]) {
565
566 case '#':
567 lsym = lsym_preprocessing;
568 next_unary = ps.next_unary;
569 break;
570
571 case '\n':
572 /* if data has been exhausted, the '\n' is a dummy. */
573 lsym = had_eof ? lsym_eof : lsym_newline;
574 next_unary = ps.next_unary;
575 break;
576
577 /* INDENT OFF */
578 case '(': lsym = lsym_lparen; next_unary = true; break;
579 case ')': lsym = lsym_rparen; next_unary = false; break;
580 case '[': lsym = lsym_lbracket; next_unary = true; break;
581 case ']': lsym = lsym_rbracket; next_unary = false; break;
582 case '{': lsym = lsym_lbrace; next_unary = true; break;
583 case '}': lsym = lsym_rbrace; next_unary = true; break;
584 case '.': lsym = lsym_period; next_unary = false; break;
585 case '?': lsym = lsym_question; next_unary = true; break;
586 case ',': lsym = lsym_comma; next_unary = true; break;
587 case ';': lsym = lsym_semicolon; next_unary = true; break;
588 /* INDENT ON */
589
590 case '+':
591 case '-':
592 lsym = ps.next_unary ? lsym_unary_op : lsym_binary_op;
593 next_unary = true;
594
595 /* '++' or '--' */
596 if (*inp_p == token.s[token.len - 1]) {
597 token_add_char(*inp_p++);
598 if (ps.prev_lsym == lsym_word ||
599 ps.prev_lsym == lsym_rparen ||
600 ps.prev_lsym == lsym_rbracket) {
601 lsym = ps.next_unary
602 ? lsym_unary_op : lsym_postfix_op;
603 next_unary = false;
604 }
605
606 } else if (*inp_p == '=') { /* '+=' or '-=' */
607 token_add_char(*inp_p++);
608
609 } else if (*inp_p == '>') { /* '->' */
610 token_add_char(*inp_p++);
611 lsym = lsym_unary_op;
612 next_unary = false;
613 ps.want_blank = false;
614 }
615 break;
616
617 case ':':
618 lsym = ps.quest_level > 0
619 ? (ps.quest_level--, lsym_question_colon)
620 : ps.in_var_decl ? lsym_other_colon : lsym_label_colon;
621 next_unary = true;
622 break;
623
624 case '*':
625 if (*inp_p == '=') {
626 token_add_char(*inp_p++);
627 lsym = lsym_binary_op;
628 } else if (is_asterisk_pointer()) {
629 lex_asterisk_pointer();
630 lsym = lsym_unary_op;
631 } else
632 lsym = lsym_binary_op;
633 next_unary = true;
634 break;
635
636 case '=':
637 if (ps.in_var_decl)
638 ps.in_init = true;
639 if (*inp_p == '=')
640 token_add_char(*inp_p++);
641 lsym = lsym_binary_op;
642 next_unary = true;
643 break;
644
645 case '>':
646 case '<':
647 case '!': /* ops like <, <<, <=, !=, etc. */
648 if (*inp_p == '>' || *inp_p == '<' || *inp_p == '=')
649 token_add_char(*inp_p++);
650 if (*inp_p == '=')
651 token_add_char(*inp_p++);
652 lsym = ps.next_unary ? lsym_unary_op : lsym_binary_op;
653 next_unary = true;
654 break;
655
656 case '\'':
657 case '"':
658 lex_char_or_string();
659 lsym = lsym_word;
660 next_unary = false;
661 break;
662
663 default:
664 if (token.s[token.len - 1] == '/'
665 && (*inp_p == '*' || *inp_p == '/')) {
666 enum indent_enabled prev = indent_enabled;
667 lex_indent_comment();
668 if (prev == indent_on && indent_enabled == indent_off)
669 buf_clear(&out.indent_off_text);
670 token_add_char(*inp_p++);
671 lsym = lsym_comment;
672 next_unary = ps.next_unary;
673 break;
674 }
675
676 /* punctuation like '%', '&&', '/', '^', '||', '~' */
677 lsym = ps.next_unary ? lsym_unary_op : lsym_binary_op;
678 if (*inp_p == token.s[token.len - 1])
679 token_add_char(*inp_p++), lsym = lsym_binary_op;
680 if (*inp_p == '=')
681 token_add_char(*inp_p++), lsym = lsym_binary_op;
682
683 next_unary = true;
684 }
685
686 ps.next_unary = next_unary;
687
688 return lsym;
689 }
690