lexi.c revision 1.183 1 /* $NetBSD: lexi.c,v 1.183 2023/05/14 14:14:07 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.183 2023/05/14 14:14:07 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_storage_class},
60 {"bool", lsym_type},
61 {"break", lsym_word},
62 {"case", lsym_case_label},
63 {"char", lsym_type},
64 {"complex", lsym_type},
65 {"const", lsym_type},
66 {"continue", lsym_word},
67 {"default", lsym_case_label},
68 {"do", lsym_do},
69 {"double", lsym_type},
70 {"else", lsym_else},
71 {"enum", lsym_tag},
72 {"extern", lsym_storage_class},
73 {"float", lsym_type},
74 {"for", lsym_for},
75 {"goto", lsym_word},
76 {"if", lsym_if},
77 {"imaginary", lsym_type},
78 {"inline", lsym_word},
79 {"int", lsym_type},
80 {"long", lsym_type},
81 {"offsetof", lsym_offsetof},
82 {"register", lsym_storage_class},
83 {"restrict", lsym_word},
84 {"return", lsym_return},
85 {"short", lsym_type},
86 {"signed", lsym_type},
87 {"sizeof", lsym_sizeof},
88 {"static", lsym_storage_class},
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_type},
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 static void
170 check_size_token(size_t desired_size)
171 {
172 if (token.e + desired_size >= token.limit)
173 buf_expand(&token, desired_size);
174 }
175
176 static void
177 token_add_char(char ch)
178 {
179 check_size_token(1);
180 *token.e++ = ch;
181 }
182
183
184 static lexer_symbol
185 lexi_end(lexer_symbol lsym)
186 {
187 #ifdef debug
188 debug_parser_state(lsym);
189 #endif
190 return lsym;
191 }
192
193 static void
194 lex_number(void)
195 {
196 for (unsigned char s = 'A'; s != 'f' && s != 'i' && s != 'u';) {
197 unsigned char ch = (unsigned char)inp_peek();
198 if (ch == '\\' && inp_lookahead(1) == '\n') {
199 inp_skip();
200 inp_skip();
201 line_no++;
202 continue;
203 }
204 if (ch >= array_length(lex_number_row) || lex_number_row[ch] == 0)
205 break;
206
207 unsigned char row = lex_number_row[ch];
208 if (lex_number_state[row][s - 'A'] == ' ') {
209 /*-
210 * lex_number_state[0][s - 'A'] now indicates the type:
211 * f = floating, i = integer, u = unknown
212 */
213 return;
214 }
215
216 s = lex_number_state[row][s - 'A'];
217 token_add_char(inp_next());
218 }
219 }
220
221 static bool
222 is_identifier_start(char ch)
223 {
224 return ch_isalpha(ch) || ch == '_' || ch == '$';
225 }
226
227 static bool
228 is_identifier_part(char ch)
229 {
230 return ch_isalnum(ch) || ch == '_' || ch == '$';
231 }
232
233 static void
234 lex_word(void)
235 {
236 for (;;) {
237 if (is_identifier_part(inp_peek()))
238 token_add_char(inp_next());
239 else if (inp_peek() == '\\' && inp_lookahead(1) == '\n') {
240 inp_skip();
241 inp_skip();
242 } else
243 return;
244 }
245 }
246
247 static void
248 lex_char_or_string(void)
249 {
250 for (char delim = token.e[-1];;) {
251 if (inp_peek() == '\n') {
252 diag(1, "Unterminated literal");
253 return;
254 }
255
256 token_add_char(inp_next());
257 if (token.e[-1] == delim)
258 return;
259
260 if (token.e[-1] == '\\') {
261 if (inp_peek() == '\n')
262 ++line_no;
263 token_add_char(inp_next());
264 }
265 }
266 }
267
268 /* Guess whether the current token is a declared type. */
269 static bool
270 probably_typename(void)
271 {
272 if (ps.prev_token == lsym_storage_class)
273 return true;
274 if (ps.block_init)
275 return false;
276 if (ps.in_stmt_or_decl) /* XXX: this condition looks incorrect */
277 return false;
278 if (inp_peek() == '*' && inp_lookahead(1) != '=')
279 goto maybe;
280 /* XXX: is_identifier_start */
281 if (ch_isalpha(inp_peek()))
282 goto maybe;
283 return false;
284 maybe:
285 return ps.prev_token == lsym_semicolon ||
286 ps.prev_token == lsym_lbrace ||
287 ps.prev_token == lsym_rbrace;
288 }
289
290 static int
291 bsearch_typenames(const char *key)
292 {
293 const char **arr = typenames.items;
294 int lo = 0;
295 int hi = (int)typenames.len - 1;
296
297 while (lo <= hi) {
298 int mid = (int)((unsigned)(lo + hi) >> 1);
299 int cmp = strcmp(arr[mid], key);
300 if (cmp < 0)
301 lo = mid + 1;
302 else if (cmp > 0)
303 hi = mid - 1;
304 else
305 return mid;
306 }
307 return -(lo + 1);
308 }
309
310 static bool
311 is_typename(void)
312 {
313 if (opt.auto_typedefs &&
314 token.e - token.s >= 2 && memcmp(token.e - 2, "_t", 2) == 0)
315 return true;
316
317 return bsearch_typenames(token.s) >= 0;
318 }
319
320 static int
321 cmp_keyword_by_name(const void *key, const void *elem)
322 {
323 return strcmp(key, ((const struct keyword *)elem)->name);
324 }
325
326 /*
327 * Looking at something like 'function_name(...)' in a line, guess whether
328 * this starts a function definition or a declaration.
329 */
330 static bool
331 probably_looking_at_definition(void)
332 {
333 int paren_level = 0;
334 for (const char *p = inp_p(); *p != '\n'; p++) {
335 if (*p == '(')
336 paren_level++;
337 if (*p == ')' && --paren_level == 0) {
338 p++;
339
340 while (*p != '\n' && (ch_isspace(*p) || is_identifier_part(*p)))
341 p++; /* '__dead' or '__unused' */
342
343 if (*p == '\n') /* func(...) */
344 break;
345 if (*p == ';') /* func(...); */
346 return false;
347 if (*p == ',') /* double abs(), pi; */
348 return false;
349 if (*p == '(') /* func(...) __attribute__((...)) */
350 paren_level++; /* func(...) __printflike(...) */
351 else
352 break; /* func(...) { ... */
353 }
354 }
355
356 /*
357 * To further reduce the cases where indent wrongly treats an incomplete
358 * function declaration as a function definition, thus adding a newline
359 * before the function name, it may be worth looking for parameter names,
360 * as these are often omitted in function declarations and only included
361 * in function definitions. Or just increase the lookahead to more than
362 * just the current line of input, until the next '{'.
363 */
364 return true;
365 }
366
367 /* Read an alphanumeric token into 'token', or return lsym_eof. */
368 static lexer_symbol
369 lexi_alnum(void)
370 {
371 if (ch_isdigit(inp_peek()) ||
372 (inp_peek() == '.' && ch_isdigit(inp_lookahead(1)))) {
373 lex_number();
374 } else if (is_identifier_start(inp_peek())) {
375 lex_word();
376
377 if (token.s[0] == 'L' && token.e - token.s == 1 &&
378 (inp_peek() == '"' || inp_peek() == '\'')) {
379 token_add_char(inp_next());
380 lex_char_or_string();
381 ps.next_unary = false;
382
383 check_size_token(1);
384 *token.e = '\0';
385
386 return lsym_word;
387 }
388 } else
389 return lsym_eof; /* just as a placeholder */
390
391 *token.e = '\0';
392
393 while (ch_isblank(inp_peek()))
394 inp_skip();
395
396 ps.next_unary = ps.prev_token == lsym_tag; /* for 'struct s *' */
397
398 if (ps.prev_token == lsym_tag && ps.nparen == 0)
399 return lsym_type_outside_parentheses;
400
401 const struct keyword *kw = bsearch(token.s, keywords,
402 array_length(keywords), sizeof(keywords[0]), cmp_keyword_by_name);
403 bool is_type = false;
404 if (kw == NULL) {
405 if (is_typename()) {
406 is_type = true;
407 ps.next_unary = true;
408 if (ps.in_enum == in_enum_enum)
409 ps.in_enum = in_enum_type;
410 goto found_typename;
411 }
412
413 } else { /* we have a keyword */
414 is_type = kw->lsym == lsym_type;
415 ps.next_unary = true;
416 if (kw->lsym != lsym_tag && kw->lsym != lsym_type)
417 return kw->lsym;
418
419 found_typename:
420 if (ps.nparen > 0) {
421 /* inside parentheses: cast, param list, offsetof or sizeof */
422 if (!ps.paren[ps.nparen - 1].no_cast)
423 ps.paren[ps.nparen - 1].maybe_cast = true;
424 }
425 if (ps.prev_token != lsym_period && ps.prev_token != lsym_unary_op) {
426 if (kw != NULL && kw->lsym == lsym_tag) {
427 if (token.s[0] == 'e' /* enum */)
428 ps.in_enum = in_enum_enum;
429 return lsym_tag;
430 }
431 if (ps.nparen == 0)
432 return lsym_type_outside_parentheses;
433 }
434 }
435
436 if (inp_peek() == '(' && ps.tos <= 1 && ps.ind_level == 0 &&
437 !ps.in_func_def_params && !ps.block_init) {
438
439 if (ps.nparen == 0 && probably_looking_at_definition()) {
440 ps.is_function_definition = true;
441 if (ps.in_decl)
442 ps.in_func_def_params = true;
443 return lsym_funcname;
444 }
445
446 } else if (ps.nparen == 0 && probably_typename()) {
447 ps.next_unary = true;
448 return lsym_type_outside_parentheses;
449 }
450
451 return is_type ? lsym_type_in_parentheses : lsym_word;
452 }
453
454 static bool
455 is_asterisk_unary(void)
456 {
457 if (ps.next_unary || ps.in_func_def_params)
458 return true;
459 if (ps.prev_token == lsym_word ||
460 ps.prev_token == lsym_rparen_or_rbracket)
461 return false;
462 return ps.in_decl && ps.nparen > 0;
463 }
464
465 static void
466 lex_asterisk_unary(void)
467 {
468 while (inp_peek() == '*' || ch_isspace(inp_peek())) {
469 if (inp_peek() == '*')
470 token_add_char('*');
471 inp_skip();
472 }
473
474 if (ps.in_decl) {
475 for (const char *tp = inp_p(); *tp != '\n';) {
476 if (ch_isspace(*tp))
477 tp++;
478 else if (is_identifier_start(*tp)) {
479 tp++;
480 while (is_identifier_part(*tp))
481 tp++;
482 } else {
483 if (*tp == '(')
484 ps.is_function_definition = true;
485 break;
486 }
487 }
488 }
489 }
490
491 /* Reads the next token, placing it in the global variable "token". */
492 lexer_symbol
493 lexi(void)
494 {
495 token.e = token.s;
496 ps.curr_col_1 = ps.next_col_1;
497 ps.next_col_1 = false;
498
499 while (ch_isblank(inp_peek())) {
500 ps.curr_col_1 = false;
501 inp_skip();
502 }
503
504 lexer_symbol alnum_lsym = lexi_alnum();
505 if (alnum_lsym != lsym_eof)
506 return lexi_end(alnum_lsym);
507
508 /* Scan a non-alphanumeric token */
509
510 check_size_token(3); /* for things like "<<=" */
511 *token.e++ = inp_next();
512 *token.e = '\0';
513
514 lexer_symbol lsym;
515 bool next_unary;
516
517 switch (token.e[-1]) {
518
519 /* INDENT OFF */
520 case '(':
521 case '[': lsym = lsym_lparen_or_lbracket; next_unary = true; break;
522 case ')':
523 case ']': lsym = lsym_rparen_or_rbracket; next_unary = false; break;
524 case '?': lsym = lsym_question; next_unary = true; break;
525 case ':': lsym = lsym_colon; next_unary = true; break;
526 case ';': lsym = lsym_semicolon; next_unary = true; break;
527 case '{': lsym = lsym_lbrace; next_unary = true; break;
528 case '}': lsym = lsym_rbrace; next_unary = true; break;
529 case ',': lsym = lsym_comma; next_unary = true; break;
530 case '.': lsym = lsym_period; next_unary = false; break;
531 /* INDENT ON */
532
533 case '\n':
534 /* if data has been exhausted, the '\n' is a dummy. */
535 lsym = had_eof ? lsym_eof : lsym_newline;
536 next_unary = ps.next_unary;
537 ps.next_col_1 = true;
538 break;
539
540 case '\f':
541 lsym = lsym_form_feed;
542 next_unary = ps.next_unary;
543 ps.next_col_1 = true;
544 break;
545
546 case '#':
547 lsym = lsym_preprocessing;
548 next_unary = ps.next_unary;
549 break;
550
551 case '\'':
552 case '"':
553 lex_char_or_string();
554 lsym = lsym_word;
555 next_unary = false;
556 break;
557
558 case '-':
559 case '+':
560 lsym = ps.next_unary ? lsym_unary_op : lsym_binary_op;
561 next_unary = true;
562
563 if (inp_peek() == token.e[-1]) { /* '++' or '--' */
564 *token.e++ = inp_next();
565 if (ps.prev_token == lsym_word ||
566 ps.prev_token == lsym_rparen_or_rbracket) {
567 lsym = ps.next_unary ? lsym_unary_op : lsym_postfix_op;
568 next_unary = false;
569 }
570
571 } else if (inp_peek() == '=') { /* '+=' or '-=' */
572 *token.e++ = inp_next();
573
574 } else if (inp_peek() == '>') { /* '->' */
575 *token.e++ = inp_next();
576 lsym = lsym_unary_op;
577 next_unary = false;
578 ps.want_blank = false;
579 }
580 break;
581
582 case '=':
583 if (ps.init_or_struct)
584 ps.block_init = true;
585 if (inp_peek() == '=') { /* == */
586 *token.e++ = inp_next();
587 *token.e = '\0';
588 }
589 lsym = lsym_binary_op;
590 next_unary = true;
591 break;
592
593 case '>':
594 case '<':
595 case '!': /* ops like <, <<, <=, !=, etc */
596 if (inp_peek() == '>' || inp_peek() == '<' || inp_peek() == '=')
597 *token.e++ = inp_next();
598 if (inp_peek() == '=')
599 *token.e++ = inp_next();
600 lsym = ps.next_unary ? lsym_unary_op : lsym_binary_op;
601 next_unary = true;
602 break;
603
604 case '*':
605 if (is_asterisk_unary()) {
606 lex_asterisk_unary();
607 lsym = lsym_unary_op;
608 next_unary = true;
609 } else {
610 if (inp_peek() == '=')
611 *token.e++ = inp_next();
612 lsym = lsym_binary_op;
613 next_unary = true;
614 }
615 break;
616
617 default:
618 if (token.e[-1] == '/' && (inp_peek() == '*' || inp_peek() == '/')) {
619 *token.e++ = inp_next();
620 lsym = lsym_comment;
621 next_unary = ps.next_unary;
622 break;
623 }
624
625 /* handle '||', '&&', etc., and also things as in 'int *****i' */
626 while (token.e[-1] == inp_peek() || inp_peek() == '=')
627 token_add_char(inp_next());
628
629 lsym = ps.next_unary ? lsym_unary_op : lsym_binary_op;
630 next_unary = true;
631 }
632
633 if (ps.in_enum == in_enum_enum || ps.in_enum == in_enum_type)
634 ps.in_enum = lsym == lsym_lbrace ? in_enum_brace : in_enum_no;
635 if (lsym == lsym_rbrace)
636 ps.in_enum = in_enum_no;
637
638 ps.next_unary = next_unary;
639
640 check_size_token(1);
641 *token.e = '\0';
642
643 return lexi_end(lsym);
644 }
645
646 void
647 register_typename(const char *name)
648 {
649 if (typenames.len >= typenames.cap) {
650 typenames.cap = 16 + 2 * typenames.cap;
651 typenames.items = xrealloc(typenames.items,
652 sizeof(typenames.items[0]) * typenames.cap);
653 }
654
655 int pos = bsearch_typenames(name);
656 if (pos >= 0)
657 return; /* already in the list */
658
659 pos = -(pos + 1);
660 memmove(typenames.items + pos + 1, typenames.items + pos,
661 sizeof(typenames.items[0]) * (typenames.len++ - (unsigned)pos));
662 typenames.items[pos] = xstrdup(name);
663 }
664