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