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