lex.c revision 1.209 1 /* $NetBSD: lex.c,v 1.209 2024/02/03 10:56:18 rillig Exp $ */
2
3 /*
4 * Copyright (c) 1996 Christopher G. Demetriou. All Rights Reserved.
5 * Copyright (c) 1994, 1995 Jochen Pohl
6 * All Rights Reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by Jochen Pohl for
19 * The NetBSD Project.
20 * 4. The name of the author may not be used to endorse or promote products
21 * derived from this software without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 */
34
35 #if HAVE_NBTOOL_CONFIG_H
36 #include "nbtool_config.h"
37 #endif
38
39 #include <sys/cdefs.h>
40 #if defined(__RCSID)
41 __RCSID("$NetBSD: lex.c,v 1.209 2024/02/03 10:56:18 rillig Exp $");
42 #endif
43
44 #include <ctype.h>
45 #include <errno.h>
46 #include <float.h>
47 #include <limits.h>
48 #include <math.h>
49 #include <stdlib.h>
50 #include <string.h>
51
52 #include "lint1.h"
53 #include "cgram.h"
54
55 #define CHAR_MASK ((1U << CHAR_SIZE) - 1)
56
57
58 /* Current position (it's also updated when an included file is parsed) */
59 pos_t curr_pos = { "", 1, 0 };
60
61 /*
62 * Current position in C source (not updated when an included file is
63 * parsed).
64 */
65 pos_t csrc_pos = { "", 1, 0 };
66
67 bool in_gcc_attribute;
68 bool in_system_header;
69
70 /*
71 * Valid values for 'since' are 78, 90, 99, 11, 23.
72 *
73 * The C11 keywords are all taken from the reserved namespace. They are added
74 * in C99 mode as well, to make the parse error messages more useful. For
75 * example, if the keyword '_Generic' were not defined, it would be interpreted
76 * as an implicit function call, leading to a parse error.
77 *
78 * The C23 keywords are not made available in earlier modes, as they may
79 * conflict with user-defined identifiers.
80 */
81 #define kwdef(name, token, detail, since, gcc, deco) \
82 { /* CONSTCOND */ \
83 name, token, detail, \
84 (since) == 90, \
85 (since) == 99 || (since) == 11, \
86 (since) == 23, \
87 (gcc) > 0, \
88 ((deco) & 1) != 0, ((deco) & 2) != 0, ((deco) & 4) != 0, \
89 }
90 #define kwdef_token(name, token, since, gcc, deco) \
91 kwdef(name, token, {false}, since, gcc, deco)
92 #define kwdef_sclass(name, sclass, since, gcc, deco) \
93 kwdef(name, T_SCLASS, .u.kw_scl = (sclass), since, gcc, deco)
94 #define kwdef_type(name, tspec, since) \
95 kwdef(name, T_TYPE, .u.kw_tspec = (tspec), since, 0, 1)
96 #define kwdef_tqual(name, tqual, since, gcc, deco) \
97 kwdef(name, T_QUAL, .u.kw_tqual = {.tqual = true}, since, gcc, deco)
98 #define kwdef_keyword(name, token) \
99 kwdef(name, token, {false}, 78, 0, 1)
100
101 /* During initialization, these keywords are written to the symbol table. */
102 static const struct keyword {
103 const char kw_name[20];
104 int kw_token; /* token to be returned by yylex() */
105 union {
106 bool kw_dummy;
107 scl_t kw_scl; /* if kw_token is T_SCLASS */
108 tspec_t kw_tspec; /* if kw_token is T_TYPE or
109 * T_STRUCT_OR_UNION */
110 type_qualifiers kw_tqual; /* if kw_token is T_QUAL */
111 function_specifier kw_fs; /* if kw_token is
112 * T_FUNCTION_SPECIFIER */
113 } u;
114 bool kw_added_in_c90:1;
115 bool kw_added_in_c99_or_c11:1;
116 bool kw_added_in_c23:1;
117 bool kw_gcc:1; /* available in GCC mode */
118 bool kw_plain:1; /* 'name' */
119 bool kw_leading:1; /* '__name' */
120 bool kw_both:1; /* '__name__' */
121 } keywords[] = {
122 // TODO: _Alignas is not available in C99.
123 kwdef_keyword( "_Alignas", T_ALIGNAS),
124 // TODO: _Alignof is not available in C99.
125 kwdef_keyword( "_Alignof", T_ALIGNOF),
126 // TODO: alignof is not available in C99.
127 kwdef_token( "alignof", T_ALIGNOF, 78,0,6),
128 kwdef_token( "asm", T_ASM, 78,1,7),
129 kwdef_token( "_Atomic", T_ATOMIC, 11,0,1),
130 kwdef_token( "attribute", T_ATTRIBUTE, 78,1,6),
131 kwdef_sclass( "auto", AUTO, 78,0,1),
132 kwdef_type( "_Bool", BOOL, 99),
133 kwdef_keyword( "break", T_BREAK),
134 kwdef_token( "__builtin_offsetof", T_BUILTIN_OFFSETOF, 78,1,1),
135 kwdef_keyword( "case", T_CASE),
136 kwdef_type( "char", CHAR, 78),
137 kwdef_type( "_Complex", COMPLEX, 99),
138 kwdef_tqual( "const", tq_const, 90,0,7),
139 kwdef_keyword( "continue", T_CONTINUE),
140 kwdef_keyword( "default", T_DEFAULT),
141 kwdef_keyword( "do", T_DO),
142 kwdef_type( "double", DOUBLE, 78),
143 kwdef_keyword( "else", T_ELSE),
144 // XXX: enum is not available in traditional C.
145 kwdef_keyword( "enum", T_ENUM),
146 kwdef_token( "__extension__",T_EXTENSION, 78,1,1),
147 kwdef_sclass( "extern", EXTERN, 78,0,1),
148 kwdef_type( "float", FLOAT, 78),
149 kwdef_keyword( "for", T_FOR),
150 kwdef_token( "_Generic", T_GENERIC, 11,0,1),
151 kwdef_keyword( "goto", T_GOTO),
152 kwdef_keyword( "if", T_IF),
153 kwdef_token( "__imag__", T_IMAG, 78,1,1),
154 kwdef("inline", T_FUNCTION_SPECIFIER, .u.kw_fs = FS_INLINE, 99,0,7),
155 kwdef_type( "int", INT, 78),
156 #ifdef INT128_SIZE
157 kwdef_type( "__int128_t", INT128, 99),
158 #endif
159 kwdef_type( "long", LONG, 78),
160 kwdef("_Noreturn", T_FUNCTION_SPECIFIER, .u.kw_fs = FS_NORETURN, 11,0,1),
161 // XXX: __packed is GCC-specific.
162 kwdef_token( "__packed", T_PACKED, 78,0,1),
163 kwdef_token( "__real__", T_REAL, 78,1,1),
164 kwdef_sclass( "register", REG, 78,0,1),
165 kwdef_tqual( "restrict", tq_restrict, 99,0,7),
166 kwdef_keyword( "return", T_RETURN),
167 kwdef_type( "short", SHORT, 78),
168 kwdef( "signed", T_TYPE, .u.kw_tspec = SIGNED, 90,0,3),
169 kwdef_keyword( "sizeof", T_SIZEOF),
170 kwdef_sclass( "static", STATIC, 78,0,1),
171 // XXX: _Static_assert was added in C11.
172 kwdef_keyword( "_Static_assert", T_STATIC_ASSERT),
173 kwdef("struct", T_STRUCT_OR_UNION, .u.kw_tspec = STRUCT, 78,0,1),
174 kwdef_keyword( "switch", T_SWITCH),
175 kwdef_token( "__symbolrename", T_SYMBOLRENAME, 78,0,1),
176 kwdef_sclass( "__thread", THREAD_LOCAL, 78,1,1),
177 kwdef_sclass( "_Thread_local", THREAD_LOCAL, 11,0,1),
178 kwdef_sclass( "thread_local", THREAD_LOCAL, 23,0,1),
179 kwdef_sclass( "typedef", TYPEDEF, 78,0,1),
180 kwdef_token( "typeof", T_TYPEOF, 78,1,7),
181 #ifdef INT128_SIZE
182 kwdef_type( "__uint128_t", UINT128, 99),
183 #endif
184 kwdef("union", T_STRUCT_OR_UNION, .u.kw_tspec = UNION, 78,0,1),
185 kwdef_type( "unsigned", UNSIGN, 78),
186 // XXX: void is not available in traditional C.
187 kwdef_type( "void", VOID, 78),
188 kwdef_tqual( "volatile", tq_volatile, 90,0,7),
189 kwdef_keyword( "while", T_WHILE),
190 #undef kwdef
191 #undef kwdef_token
192 #undef kwdef_sclass
193 #undef kwdef_type
194 #undef kwdef_tqual
195 #undef kwdef_keyword
196 };
197
198 /*
199 * The symbol table containing all keywords, identifiers and labels. The hash
200 * entries are linked via sym_t.s_symtab_next.
201 */
202 static sym_t *symtab[503];
203
204 /*
205 * The kind of the next expected symbol, to distinguish the namespaces of
206 * members, labels, type tags and other identifiers.
207 */
208 symbol_kind sym_kind;
209
210
211 static unsigned int
212 hash(const char *s)
213 {
214 unsigned int v;
215 const char *p;
216
217 v = 0;
218 for (p = s; *p != '\0'; p++) {
219 v = (v << 4) + (unsigned char)*p;
220 v ^= v >> 28;
221 }
222 return v % (sizeof(symtab) / sizeof(symtab[0]));
223 }
224
225 static void
226 symtab_add(sym_t *sym)
227 {
228 unsigned int h;
229
230 h = hash(sym->s_name);
231 if ((sym->s_symtab_next = symtab[h]) != NULL)
232 symtab[h]->s_symtab_ref = &sym->s_symtab_next;
233 sym->s_symtab_ref = &symtab[h];
234 symtab[h] = sym;
235 }
236
237 static sym_t *
238 symtab_search(const char *name)
239 {
240
241 unsigned int h = hash(name);
242 for (sym_t *sym = symtab[h]; sym != NULL; sym = sym->s_symtab_next) {
243 if (strcmp(sym->s_name, name) != 0)
244 continue;
245 if (sym->s_keyword != NULL ||
246 sym->s_kind == sym_kind ||
247 in_gcc_attribute)
248 return sym;
249 }
250
251 return NULL;
252 }
253
254 static void
255 symtab_remove(sym_t *sym)
256 {
257
258 if ((*sym->s_symtab_ref = sym->s_symtab_next) != NULL)
259 sym->s_symtab_next->s_symtab_ref = sym->s_symtab_ref;
260 sym->s_symtab_next = NULL;
261 }
262
263 static void
264 symtab_remove_locals(void)
265 {
266
267 for (size_t i = 0; i < sizeof(symtab) / sizeof(symtab[0]); i++) {
268 for (sym_t *sym = symtab[i]; sym != NULL; ) {
269 sym_t *next = sym->s_symtab_next;
270 if (sym->s_block_level >= 1)
271 symtab_remove(sym);
272 sym = next;
273 }
274 }
275 }
276
277 #ifdef DEBUG
278 static int
279 sym_by_name(const void *va, const void *vb)
280 {
281 const sym_t *a = *(const sym_t *const *)va;
282 const sym_t *b = *(const sym_t *const *)vb;
283
284 return strcmp(a->s_name, b->s_name);
285 }
286
287 struct syms {
288 const sym_t **items;
289 size_t len;
290 size_t cap;
291 };
292
293 static void
294 syms_add(struct syms *syms, const sym_t *sym)
295 {
296 if (syms->len >= syms->cap) {
297 syms->cap *= 2;
298 syms->items = xrealloc(syms->items,
299 syms->cap * sizeof(syms->items[0]));
300 }
301 syms->items[syms->len++] = sym;
302 }
303
304 void
305 debug_symtab(void)
306 {
307 struct syms syms = { xcalloc(64, sizeof(syms.items[0])), 0, 64 };
308
309 debug_enter();
310 for (int level = -1;; level++) {
311 bool more = false;
312 size_t n = sizeof(symtab) / sizeof(symtab[0]);
313
314 syms.len = 0;
315 for (size_t i = 0; i < n; i++) {
316 for (sym_t *sym = symtab[i]; sym != NULL;) {
317 if (sym->s_block_level == level &&
318 sym->s_keyword == NULL)
319 syms_add(&syms, sym);
320 if (sym->s_block_level > level)
321 more = true;
322 sym = sym->s_symtab_next;
323 }
324 }
325
326 if (syms.len > 0) {
327 debug_step("symbol table level %d", level);
328 debug_indent_inc();
329 qsort(syms.items, syms.len, sizeof(syms.items[0]),
330 sym_by_name);
331 for (size_t i = 0; i < syms.len; i++)
332 debug_sym("", syms.items[i], "\n");
333 debug_indent_dec();
334
335 lint_assert(level != -1);
336 }
337
338 if (!more)
339 break;
340 }
341 debug_leave();
342
343 free(syms.items);
344 }
345 #endif
346
347 static void
348 add_keyword(const struct keyword *kw, bool leading, bool trailing)
349 {
350
351 const char *name;
352 if (!leading && !trailing) {
353 name = kw->kw_name;
354 } else {
355 char buf[256];
356 (void)snprintf(buf, sizeof(buf), "%s%s%s",
357 leading ? "__" : "", kw->kw_name, trailing ? "__" : "");
358 name = xstrdup(buf);
359 }
360
361 sym_t *sym = block_zero_alloc(sizeof(*sym), "sym");
362 sym->s_name = name;
363 sym->s_keyword = kw;
364 int tok = kw->kw_token;
365 sym->u.s_keyword.sk_token = tok;
366 if (tok == T_TYPE || tok == T_STRUCT_OR_UNION)
367 sym->u.s_keyword.u.sk_tspec = kw->u.kw_tspec;
368 if (tok == T_SCLASS)
369 sym->s_scl = kw->u.kw_scl;
370 if (tok == T_QUAL)
371 sym->u.s_keyword.u.sk_type_qualifier = kw->u.kw_tqual;
372 if (tok == T_FUNCTION_SPECIFIER)
373 sym->u.s_keyword.u.function_specifier = kw->u.kw_fs;
374
375 symtab_add(sym);
376 }
377
378 static bool
379 is_keyword_known(const struct keyword *kw)
380 {
381
382 if (kw->kw_added_in_c23 && !allow_c23)
383 return false;
384 if ((kw->kw_added_in_c90 || kw->kw_added_in_c99_or_c11) && !allow_c90)
385 return false;
386
387 /*
388 * In the 1990s, GCC defined several keywords that were later
389 * incorporated into C99, therefore in GCC mode, all C99 keywords are
390 * made available. The C11 keywords are made available as well, but
391 * there are so few that they don't matter practically.
392 */
393 if (allow_gcc)
394 return true;
395 if (kw->kw_gcc)
396 return false;
397
398 if (kw->kw_added_in_c99_or_c11 && !allow_c99)
399 return false;
400 return true;
401 }
402
403 /* Write all keywords to the symbol table. */
404 void
405 initscan(void)
406 {
407
408 size_t n = sizeof(keywords) / sizeof(keywords[0]);
409 for (size_t i = 0; i < n; i++) {
410 const struct keyword *kw = keywords + i;
411 if (!is_keyword_known(kw))
412 continue;
413 if (kw->kw_plain)
414 add_keyword(kw, false, false);
415 if (kw->kw_leading)
416 add_keyword(kw, true, false);
417 if (kw->kw_both)
418 add_keyword(kw, true, true);
419 }
420 }
421
422 /*
423 * When scanning the remainder of a long token (see lex_input), read a byte
424 * and return it as an unsigned char or as EOF.
425 *
426 * Increment the line counts if necessary.
427 */
428 static int
429 read_byte(void)
430 {
431 int c;
432
433 if ((c = lex_input()) == EOF)
434 return c;
435 if (c == '\0')
436 return EOF; /* lex returns 0 on EOF. */
437 if (c == '\n')
438 lex_next_line();
439 return c;
440 }
441
442 static int
443 lex_keyword(sym_t *sym)
444 {
445 int tok = sym->u.s_keyword.sk_token;
446
447 if (tok == T_SCLASS)
448 yylval.y_scl = sym->s_scl;
449 if (tok == T_TYPE || tok == T_STRUCT_OR_UNION)
450 yylval.y_tspec = sym->u.s_keyword.u.sk_tspec;
451 if (tok == T_QUAL)
452 yylval.y_type_qualifiers =
453 sym->u.s_keyword.u.sk_type_qualifier;
454 if (tok == T_FUNCTION_SPECIFIER)
455 yylval.y_function_specifier =
456 sym->u.s_keyword.u.function_specifier;
457 return tok;
458 }
459
460 /*
461 * Look up the definition of a name in the symbol table. This symbol must
462 * either be a keyword or a symbol of the type required by sym_kind (label,
463 * member, tag, ...).
464 */
465 extern int
466 lex_name(const char *yytext, size_t yyleng)
467 {
468
469 sym_t *sym = symtab_search(yytext);
470 if (sym != NULL && sym->s_keyword != NULL)
471 return lex_keyword(sym);
472
473 sbuf_t *sb = xmalloc(sizeof(*sb));
474 sb->sb_len = yyleng;
475 sb->sb_sym = sym;
476 yylval.y_name = sb;
477
478 if (sym != NULL) {
479 lint_assert(block_level >= sym->s_block_level);
480 sb->sb_name = sym->s_name;
481 return sym->s_scl == TYPEDEF ? T_TYPENAME : T_NAME;
482 }
483
484 char *name = block_zero_alloc(yyleng + 1, "string");
485 (void)memcpy(name, yytext, yyleng + 1);
486 sb->sb_name = name;
487 return T_NAME;
488 }
489
490 // Determines whether the constant is signed in traditional C but unsigned in
491 // C90 and later.
492 static bool
493 is_unsigned_since_c90(tspec_t typ, uint64_t ui, int base)
494 {
495 if (!(allow_trad && allow_c90))
496 return false;
497 if (typ == INT) {
498 if (ui > TARG_INT_MAX && ui <= TARG_UINT_MAX && base != 10)
499 return true;
500 return ui > TARG_LONG_MAX;
501 }
502 return typ == LONG && ui > TARG_LONG_MAX;
503 }
504
505 static tspec_t
506 integer_constant_type(tspec_t t, uint64_t ui, int base, bool warned)
507 {
508 switch (t) {
509 case INT:
510 if (ui <= TARG_INT_MAX)
511 return INT;
512 if (ui <= TARG_UINT_MAX && base != 10 && allow_c90)
513 return UINT;
514 if (ui <= TARG_LONG_MAX)
515 return LONG;
516 if (ui <= TARG_ULONG_MAX && base != 10 && allow_c90)
517 return ULONG;
518 if (ui <= TARG_ULONG_MAX && !allow_c90)
519 return LONG;
520 if (!allow_c99) {
521 if (!warned)
522 /* integer constant out of range */
523 warning(252);
524 return allow_c90 ? ULONG : LONG;
525 }
526 if (ui <= TARG_LLONG_MAX)
527 return LLONG;
528 if (ui <= TARG_ULLONG_MAX && base != 10)
529 return ULLONG;
530 if (!warned)
531 /* integer constant out of range */
532 warning(252);
533 return ULLONG;
534 case UINT:
535 if (ui <= TARG_UINT_MAX)
536 return UINT;
537 if (ui <= TARG_ULONG_MAX)
538 return ULONG;
539 if (!allow_c99) {
540 if (!warned)
541 /* integer constant out of range */
542 warning(252);
543 return ULONG;
544 }
545 if (ui <= TARG_ULLONG_MAX)
546 return ULLONG;
547 if (!warned)
548 /* integer constant out of range */
549 warning(252);
550 return ULLONG;
551 case LONG:
552 if (ui <= TARG_LONG_MAX)
553 return LONG;
554 if (ui <= TARG_ULONG_MAX && base != 10)
555 return allow_c90 ? ULONG : LONG;
556 if (!allow_c99) {
557 if (!warned)
558 /* integer constant out of range */
559 warning(252);
560 return allow_c90 ? ULONG : LONG;
561 }
562 if (ui <= TARG_LLONG_MAX)
563 return LLONG;
564 if (ui <= TARG_ULLONG_MAX && base != 10)
565 return ULLONG;
566 if (!warned)
567 /* integer constant out of range */
568 warning(252);
569 return ULLONG;
570 case ULONG:
571 if (ui <= TARG_ULONG_MAX)
572 return ULONG;
573 if (!allow_c99) {
574 if (!warned)
575 /* integer constant out of range */
576 warning(252);
577 return ULONG;
578 }
579 if (ui <= TARG_ULLONG_MAX)
580 return ULLONG;
581 if (!warned)
582 /* integer constant out of range */
583 warning(252);
584 return ULLONG;
585 case LLONG:
586 if (ui <= TARG_LLONG_MAX)
587 return LLONG;
588 if (ui <= TARG_ULLONG_MAX && base != 10)
589 return allow_c90 ? ULLONG : LLONG;
590 if (!warned)
591 /* integer constant out of range */
592 warning(252);
593 return allow_c90 ? ULLONG : LLONG;
594 default:
595 if (ui <= TARG_ULLONG_MAX)
596 return ULLONG;
597 if (!warned)
598 /* integer constant out of range */
599 warning(252);
600 return ULLONG;
601 }
602 }
603
604 int
605 lex_integer_constant(const char *yytext, size_t yyleng, int base)
606 {
607 /* C11 6.4.4.1p5 */
608 static const tspec_t suffix_type[2][3] = {
609 { INT, LONG, LLONG, },
610 { UINT, ULONG, ULLONG, }
611 };
612
613 const char *cp = yytext;
614 size_t len = yyleng;
615
616 /* skip 0[xX] or 0[bB] */
617 if (base == 16 || base == 2) {
618 cp += 2;
619 len -= 2;
620 }
621
622 /* read suffixes */
623 unsigned l_suffix = 0, u_suffix = 0;
624 for (;; len--) {
625 char c = cp[len - 1];
626 if (c == 'l' || c == 'L')
627 l_suffix++;
628 else if (c == 'u' || c == 'U')
629 u_suffix++;
630 else
631 break;
632 }
633 if (l_suffix > 2 || u_suffix > 1) {
634 /* malformed integer constant */
635 warning(251);
636 if (l_suffix > 2)
637 l_suffix = 2;
638 if (u_suffix > 1)
639 u_suffix = 1;
640 }
641 if (!allow_c90 && u_suffix > 0) {
642 /* suffix 'U' is illegal in traditional C */
643 warning(97);
644 }
645 tspec_t ct = suffix_type[u_suffix][l_suffix];
646
647 bool warned = false;
648 errno = 0;
649 char *eptr;
650 uint64_t ui = (uint64_t)strtoull(cp, &eptr, base);
651 lint_assert(eptr == cp + len);
652 if (errno != 0) {
653 /* integer constant out of range */
654 warning(252);
655 warned = true;
656 }
657
658 if (any_query_enabled && base == 8 && ui != 0) {
659 /* octal number '%.*s' */
660 query_message(8, (int)len, cp);
661 }
662
663 bool ansiu = is_unsigned_since_c90(ct, ui, base);
664
665 tspec_t t = integer_constant_type(ct, ui, base, warned);
666 ui = (uint64_t)convert_integer((int64_t)ui, t, 0);
667
668 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
669 yylval.y_val->v_tspec = t;
670 yylval.y_val->v_unsigned_since_c90 = ansiu;
671 yylval.y_val->u.integer = (int64_t)ui;
672
673 return T_CON;
674 }
675
676 /*
677 * Extend or truncate si to match t. If t is signed, sign-extend.
678 *
679 * len is the number of significant bits. If len is 0, len is set
680 * to the width of type t.
681 */
682 int64_t
683 convert_integer(int64_t si, tspec_t t, unsigned int len)
684 {
685
686 if (len == 0)
687 len = size_in_bits(t);
688
689 uint64_t vbits = value_bits(len);
690 uint64_t ui = (uint64_t)si;
691 return t == PTR || is_uinteger(t) || ((ui & bit(len - 1)) == 0)
692 ? (int64_t)(ui & vbits)
693 : (int64_t)(ui | ~vbits);
694 }
695
696 int
697 lex_floating_constant(const char *yytext, size_t yyleng)
698 {
699 const char *cp = yytext;
700 size_t len = yyleng;
701
702 bool imaginary = cp[len - 1] == 'i';
703 if (imaginary)
704 len--;
705
706 char c = cp[len - 1];
707 tspec_t typ;
708 if (c == 'f' || c == 'F') {
709 typ = imaginary ? FCOMPLEX : FLOAT;
710 len--;
711 } else if (c == 'l' || c == 'L') {
712 typ = imaginary ? LCOMPLEX : LDOUBLE;
713 len--;
714 } else
715 typ = imaginary ? DCOMPLEX : DOUBLE;
716
717 if (!allow_c90 && typ != DOUBLE) {
718 /* suffixes 'F' and 'L' are illegal in traditional C */
719 warning(98);
720 }
721
722 errno = 0;
723 char *eptr;
724 long double ld = strtold(cp, &eptr);
725 lint_assert(eptr == cp + len);
726 if (errno != 0) {
727 /* floating-point constant out of range */
728 warning(248);
729 } else if (typ == FLOAT) {
730 ld = (float)ld;
731 if (isfinite(ld) == 0) {
732 /* floating-point constant out of range */
733 warning(248);
734 ld = ld > 0 ? FLT_MAX : -FLT_MAX;
735 }
736 } else if (typ == DOUBLE
737 || /* CONSTCOND */ LDOUBLE_SIZE == DOUBLE_SIZE) {
738 ld = (double)ld;
739 if (isfinite(ld) == 0) {
740 /* floating-point constant out of range */
741 warning(248);
742 ld = ld > 0 ? DBL_MAX : -DBL_MAX;
743 }
744 }
745
746 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
747 yylval.y_val->v_tspec = typ;
748 yylval.y_val->u.floating = ld;
749
750 return T_CON;
751 }
752
753 int
754 lex_operator(int t, op_t o)
755 {
756
757 yylval.y_op = o;
758 return t;
759 }
760
761 static int prev_byte = -1;
762
763 static int
764 read_escaped_oct(int c, bool wide)
765 {
766 int n = 3;
767 int value = 0;
768 do {
769 value = (value << 3) + (c - '0');
770 c = read_byte();
771 } while (--n > 0 && '0' <= c && c <= '7');
772 prev_byte = c;
773 if (value > TARG_UCHAR_MAX && !wide) {
774 /* character escape does not fit in character */
775 warning(76);
776 value &= CHAR_MASK;
777 }
778 return value;
779 }
780
781 static unsigned int
782 read_escaped_hex(int c, bool wide)
783 {
784 if (!allow_c90)
785 /* \x undefined in traditional C */
786 warning(82);
787 uint64_t value = 0;
788 uint64_t mask = value_bits(wide ? 32 : CHAR_SIZE);
789 int state = 0; /* 0 = no digits, 1 = OK, 2 = overflow */
790 while (c = read_byte(), isxdigit(c)) {
791 c = isdigit(c) ? c - '0' : toupper(c) - 'A' + 10;
792 value = (value << 4) + c;
793 if (state == 2)
794 continue;
795 if ((value & ~mask) != 0) {
796 /* overflow in hex escape */
797 warning(75);
798 state = 2;
799 } else {
800 state = 1;
801 }
802 }
803 prev_byte = c;
804 if (state == 0) {
805 /* no hex digits follow \x */
806 error(74);
807 }
808 if (state == 2)
809 value &= mask;
810 return (unsigned int)value;
811 }
812
813 static int
814 read_escaped_backslash(int delim, bool wide)
815 {
816 int c;
817
818 switch (c = read_byte()) {
819 case '"':
820 if (!allow_c90 && delim == '\'')
821 /* \" inside character constants undef... */
822 warning(262);
823 return '"';
824 case '\'':
825 return '\'';
826 case '?':
827 if (!allow_c90)
828 /* \? undefined in traditional C */
829 warning(263);
830 return '?';
831 case '\\':
832 return '\\';
833 case 'a':
834 if (!allow_c90)
835 /* \a undefined in traditional C */
836 warning(81);
837 return '\a';
838 case 'b':
839 return '\b';
840 case 'e':
841 if (!allow_gcc)
842 break;
843 /* Not in the C standard yet, compilers recognize it */
844 /* LINTED 79 */
845 return '\e';
846 case 'f':
847 return '\f';
848 case 'n':
849 return '\n';
850 case 'r':
851 return '\r';
852 case 't':
853 return '\t';
854 case 'v':
855 if (!allow_c90)
856 /* \v undefined in traditional C */
857 warning(264);
858 return '\v';
859 case '8': case '9':
860 /* bad octal digit '%c' */
861 warning(77, c);
862 /* FALLTHROUGH */
863 case '0': case '1': case '2': case '3':
864 case '4': case '5': case '6': case '7':
865 return read_escaped_oct(c, wide);
866 case 'x':
867 return (int)read_escaped_hex(c, wide);
868 case '\n':
869 return -3;
870 case EOF:
871 return -2;
872 default:
873 break;
874 }
875 if (isprint(c))
876 /* dubious escape \%c */
877 warning(79, c);
878 else
879 /* dubious escape \%o */
880 warning(80, c);
881 return c;
882 }
883
884 /*
885 * Read a character which is part of a character constant or of a string
886 * and handle escapes.
887 *
888 * 'delim' is '\'' for character constants and '"' for string literals.
889 *
890 * Returns -1 if the end of the character constant or string is reached,
891 * -2 if the EOF is reached, and the character otherwise.
892 */
893 static int
894 get_escaped_char(int delim, bool wide)
895 {
896
897 int c = prev_byte;
898 if (c != -1)
899 prev_byte = -1;
900 else
901 c = read_byte();
902
903 if (c == delim)
904 return -1;
905 switch (c) {
906 case '\n':
907 /* newline in string or char constant */
908 error(254);
909 return -2;
910 case '\0':
911 /* syntax error '%s' */
912 error(249, "EOF or null byte in literal");
913 return -2;
914 case EOF:
915 return -2;
916 case '\\':
917 c = read_escaped_backslash(delim, wide);
918 if (c == -3)
919 return get_escaped_char(delim, wide);
920 break;
921 default:
922 if (c != ' ' && (isspace(c) || iscntrl(c))) {
923 /* invisible character U+%04X in %s */
924 query_message(17, (unsigned int)c, delim == '"'
925 ? "string literal" : "character constant");
926 }
927 }
928 return c;
929 }
930
931 /* Called if lex found a leading "'". */
932 int
933 lex_character_constant(void)
934 {
935 size_t n;
936 int val, c;
937
938 n = 0;
939 val = 0;
940 while ((c = get_escaped_char('\'', false)) >= 0) {
941 val = (int)((unsigned int)val << CHAR_SIZE) + c;
942 n++;
943 }
944 if (c == -2) {
945 /* unterminated character constant */
946 error(253);
947 } else if (n > sizeof(int) || (n > 1 && (pflag || hflag))) {
948 /*
949 * XXX: ^^ should rather be sizeof(TARG_INT). Luckily,
950 * sizeof(int) is the same on all supported platforms.
951 */
952 /* too many characters in character constant */
953 error(71);
954 } else if (n > 1) {
955 /* multi-character character constant */
956 warning(294);
957 } else if (n == 0) {
958 /* empty character constant */
959 error(73);
960 }
961 if (n == 1)
962 val = (int)convert_integer(val, CHAR, CHAR_SIZE);
963
964 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
965 yylval.y_val->v_tspec = INT;
966 yylval.y_val->v_char_constant = true;
967 yylval.y_val->u.integer = val;
968
969 return T_CON;
970 }
971
972 /*
973 * Called if lex found a leading L\'
974 */
975 int
976 lex_wide_character_constant(void)
977 {
978 static char buf[MB_LEN_MAX + 1];
979 size_t n, nmax;
980 int c;
981 wchar_t wc;
982
983 nmax = MB_CUR_MAX;
984
985 n = 0;
986 while ((c = get_escaped_char('\'', true)) >= 0) {
987 if (n < nmax)
988 buf[n] = (char)c;
989 n++;
990 }
991
992 wc = 0;
993
994 if (c == -2) {
995 /* unterminated character constant */
996 error(253);
997 } else if (n == 0) {
998 /* empty character constant */
999 error(73);
1000 } else if (n > nmax) {
1001 n = nmax;
1002 /* too many characters in character constant */
1003 error(71);
1004 } else {
1005 buf[n] = '\0';
1006 (void)mbtowc(NULL, NULL, 0);
1007 if (mbtowc(&wc, buf, nmax) < 0)
1008 /* invalid multibyte character */
1009 error(291);
1010 }
1011
1012 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
1013 yylval.y_val->v_tspec = WCHAR_TSPEC;
1014 yylval.y_val->v_char_constant = true;
1015 yylval.y_val->u.integer = wc;
1016
1017 return T_CON;
1018 }
1019
1020 /* See https://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html */
1021 static void
1022 parse_line_directive_flags(const char *p,
1023 bool *is_begin, bool *is_end, bool *is_system)
1024 {
1025
1026 *is_begin = false;
1027 *is_end = false;
1028 *is_system = false;
1029
1030 while (*p != '\0') {
1031 while (ch_isspace(*p))
1032 p++;
1033
1034 const char *word = p;
1035 while (*p != '\0' && !ch_isspace(*p))
1036 p++;
1037 size_t len = (size_t)(p - word);
1038
1039 if (len == 1 && word[0] == '1')
1040 *is_begin = true;
1041 if (len == 1 && word[0] == '2')
1042 *is_end = true;
1043 if (len == 1 && word[0] == '3')
1044 *is_system = true;
1045 /* Flag '4' is only interesting for C++. */
1046 }
1047 }
1048
1049 /*
1050 * The first directive of the preprocessed translation unit provides the name
1051 * of the C source file as specified at the command line.
1052 */
1053 static void
1054 set_csrc_pos(void)
1055 {
1056 static bool done;
1057
1058 if (done)
1059 return;
1060 done = true;
1061 csrc_pos.p_file = curr_pos.p_file;
1062 outsrc(transform_filename(curr_pos.p_file, strlen(curr_pos.p_file)));
1063 }
1064
1065 /*
1066 * Called for preprocessor directives. Currently implemented are:
1067 * # pragma [argument...]
1068 * # lineno
1069 * # lineno "filename" [GCC-flag...]
1070 */
1071 void
1072 lex_directive(const char *yytext)
1073 {
1074 const char *p = yytext + 1; /* skip '#' */
1075
1076 while (*p == ' ' || *p == '\t')
1077 p++;
1078
1079 if (!ch_isdigit(*p)) {
1080 if (strncmp(p, "pragma", 6) == 0 && ch_isspace(p[6]))
1081 return;
1082 goto error;
1083 }
1084
1085 char *end;
1086 long ln = strtol(--p, &end, 10);
1087 if (end == p)
1088 goto error;
1089 p = end;
1090
1091 if (*p != ' ' && *p != '\t' && *p != '\0')
1092 goto error;
1093 while (*p == ' ' || *p == '\t')
1094 p++;
1095
1096 if (*p != '\0') {
1097 if (*p != '"')
1098 goto error;
1099 const char *fn = ++p;
1100 while (*p != '"' && *p != '\0')
1101 p++;
1102 if (*p != '"')
1103 goto error;
1104 size_t fn_len = p++ - fn;
1105 if (fn_len > PATH_MAX)
1106 goto error;
1107 if (fn_len == 0) {
1108 fn = "{standard input}";
1109 fn_len = strlen(fn);
1110 }
1111 curr_pos.p_file = record_filename(fn, fn_len);
1112 set_csrc_pos();
1113
1114 bool is_begin, is_end, is_system;
1115 parse_line_directive_flags(p, &is_begin, &is_end, &is_system);
1116 update_location(curr_pos.p_file, (int)ln, is_begin, is_end);
1117 in_system_header = is_system;
1118 }
1119 curr_pos.p_line = (int)ln - 1;
1120 curr_pos.p_uniq = 0;
1121 if (curr_pos.p_file == csrc_pos.p_file) {
1122 csrc_pos.p_line = (int)ln - 1;
1123 csrc_pos.p_uniq = 0;
1124 }
1125 return;
1126
1127 error:
1128 /* undefined or invalid '#' directive */
1129 warning(255);
1130 }
1131
1132 /* Handle lint comments such as ARGSUSED. */
1133 void
1134 lex_comment(void)
1135 {
1136 int c;
1137 static const struct {
1138 const char name[18];
1139 bool arg;
1140 lint_comment comment;
1141 } keywtab[] = {
1142 { "ARGSUSED", true, LC_ARGSUSED },
1143 { "BITFIELDTYPE", false, LC_BITFIELDTYPE },
1144 { "CONSTCOND", false, LC_CONSTCOND },
1145 { "CONSTANTCOND", false, LC_CONSTCOND },
1146 { "CONSTANTCONDITION", false, LC_CONSTCOND },
1147 { "FALLTHRU", false, LC_FALLTHROUGH },
1148 { "FALLTHROUGH", false, LC_FALLTHROUGH },
1149 { "FALL THROUGH", false, LC_FALLTHROUGH },
1150 { "fallthrough", false, LC_FALLTHROUGH },
1151 { "LINTLIBRARY", false, LC_LINTLIBRARY },
1152 { "LINTED", true, LC_LINTED },
1153 { "LONGLONG", false, LC_LONGLONG },
1154 { "NOSTRICT", true, LC_LINTED },
1155 { "NOTREACHED", false, LC_NOTREACHED },
1156 { "PRINTFLIKE", true, LC_PRINTFLIKE },
1157 { "PROTOLIB", true, LC_PROTOLIB },
1158 { "SCANFLIKE", true, LC_SCANFLIKE },
1159 { "VARARGS", true, LC_VARARGS },
1160 };
1161 char keywd[32];
1162 char arg[32];
1163 size_t l, i;
1164 int a;
1165
1166 bool seen_end_of_comment = false;
1167
1168 while (c = read_byte(), isspace(c))
1169 continue;
1170
1171 /* Read the potential keyword to keywd */
1172 l = 0;
1173 while (c != EOF && l < sizeof(keywd) - 1 &&
1174 (isalpha(c) || isspace(c))) {
1175 if (islower(c) && l > 0 && ch_isupper(keywd[0]))
1176 break;
1177 keywd[l++] = (char)c;
1178 c = read_byte();
1179 }
1180 while (l > 0 && ch_isspace(keywd[l - 1]))
1181 l--;
1182 keywd[l] = '\0';
1183
1184 /* look for the keyword */
1185 for (i = 0; i < sizeof(keywtab) / sizeof(keywtab[0]); i++)
1186 if (strcmp(keywtab[i].name, keywd) == 0)
1187 goto found_keyword;
1188 goto skip_rest;
1189
1190 found_keyword:
1191 while (isspace(c))
1192 c = read_byte();
1193
1194 /* read the argument, if the keyword accepts one and there is one */
1195 l = 0;
1196 if (keywtab[i].arg) {
1197 while (isdigit(c) && l < sizeof(arg) - 1) {
1198 arg[l++] = (char)c;
1199 c = read_byte();
1200 }
1201 }
1202 arg[l] = '\0';
1203 a = l != 0 ? atoi(arg) : -1;
1204
1205 while (isspace(c))
1206 c = read_byte();
1207
1208 seen_end_of_comment = c == '*' && (c = read_byte()) == '/';
1209 if (!seen_end_of_comment && keywtab[i].comment != LC_LINTED)
1210 /* extra characters in lint comment */
1211 warning(257);
1212
1213 handle_lint_comment(keywtab[i].comment, a);
1214
1215 skip_rest:
1216 while (!seen_end_of_comment) {
1217 int lc = c;
1218 if ((c = read_byte()) == EOF) {
1219 /* unterminated comment */
1220 error(256);
1221 break;
1222 }
1223 if (lc == '*' && c == '/')
1224 seen_end_of_comment = true;
1225 }
1226 }
1227
1228 void
1229 lex_slash_slash_comment(void)
1230 {
1231 int c;
1232
1233 if (!allow_c99 && !allow_gcc)
1234 /* %s does not support '//' comments */
1235 gnuism(312, allow_c90 ? "C90" : "traditional C");
1236
1237 while ((c = read_byte()) != EOF && c != '\n')
1238 continue;
1239 }
1240
1241 /*
1242 * Clear flags for lint comments LINTED, LONGLONG and CONSTCOND.
1243 * clear_warn_flags is called after function definitions and global and
1244 * local declarations and definitions. It is also called between
1245 * the controlling expression and the body of control statements
1246 * (if, switch, for, while).
1247 */
1248 void
1249 clear_warn_flags(void)
1250 {
1251
1252 lwarn = LWARN_ALL;
1253 suppress_longlong = false;
1254 suppress_constcond = false;
1255 }
1256
1257 int
1258 lex_string(void)
1259 {
1260 buffer *buf = xcalloc(1, sizeof(*buf));
1261 buf_init(buf);
1262
1263 int c;
1264 while ((c = get_escaped_char('"', false)) >= 0)
1265 buf_add_char(buf, (char)c);
1266 if (c == -2)
1267 /* unterminated string constant */
1268 error(258);
1269
1270
1271 yylval.y_string = buf;
1272 return T_STRING;
1273 }
1274
1275 static size_t
1276 wide_length(const buffer *buf)
1277 {
1278
1279 (void)mblen(NULL, 0);
1280 size_t len = 0, i = 0;
1281 while (i < buf->len) {
1282 int n = mblen(buf->data + i, MB_CUR_MAX);
1283 if (n == -1) {
1284 /* invalid multibyte character */
1285 error(291);
1286 break;
1287 }
1288 i += n > 1 ? n : 1;
1289 len++;
1290 }
1291 return len;
1292 }
1293
1294 int
1295 lex_wide_string(void)
1296 {
1297 int c;
1298
1299 buffer buf;
1300 buf_init(&buf);
1301 while ((c = get_escaped_char('"', true)) >= 0)
1302 buf_add_char(&buf, (char)c);
1303 if (c == -2)
1304 /* unterminated string constant */
1305 error(258);
1306
1307 buffer *str = xcalloc(1, sizeof(*str));
1308 str->len = wide_length(&buf);
1309
1310 yylval.y_string = str;
1311 return T_STRING;
1312 }
1313
1314 void
1315 lex_next_line(void)
1316 {
1317 curr_pos.p_line++;
1318 curr_pos.p_uniq = 0;
1319 debug_skip_indent();
1320 debug_printf("parsing %s:%d\n", curr_pos.p_file, curr_pos.p_line);
1321 if (curr_pos.p_file == csrc_pos.p_file) {
1322 csrc_pos.p_line++;
1323 csrc_pos.p_uniq = 0;
1324 }
1325 }
1326
1327 void
1328 lex_unknown_character(int c)
1329 {
1330
1331 /* unknown character \%o */
1332 error(250, c);
1333 }
1334
1335 /*
1336 * The scanner does not create new symbol table entries for symbols it cannot
1337 * find in the symbol table. This is to avoid putting undeclared symbols into
1338 * the symbol table if a syntax error occurs.
1339 *
1340 * getsym is called as soon as it is probably ok to put the symbol in the
1341 * symbol table. It is still possible that symbols are put in the symbol
1342 * table that are not completely declared due to syntax errors. To avoid too
1343 * many problems in this case, symbols get type 'int' in getsym.
1344 *
1345 * XXX calls to getsym should be delayed until declare_1_* is called.
1346 */
1347 sym_t *
1348 getsym(sbuf_t *sb)
1349 {
1350
1351 sym_t *sym = sb->sb_sym;
1352
1353 /*
1354 * During member declaration it is possible that name() looked for
1355 * symbols of type SK_VCFT, although it should have looked for symbols
1356 * of type SK_TAG. Same can happen for labels. Both cases are
1357 * compensated here.
1358 */
1359 if (sym_kind == SK_MEMBER || sym_kind == SK_LABEL) {
1360 if (sym == NULL || sym->s_kind == SK_VCFT)
1361 sym = symtab_search(sb->sb_name);
1362 }
1363
1364 if (sym != NULL) {
1365 lint_assert(sym->s_kind == sym_kind);
1366 set_sym_kind(SK_VCFT);
1367 free(sb);
1368 return sym;
1369 }
1370
1371 /* create a new symbol table entry */
1372
1373 /* labels must always be allocated at level 1 (outermost block) */
1374 decl_level *dl;
1375 if (sym_kind == SK_LABEL) {
1376 sym = level_zero_alloc(1, sizeof(*sym), "sym");
1377 char *s = level_zero_alloc(1, sb->sb_len + 1, "string");
1378 (void)memcpy(s, sb->sb_name, sb->sb_len + 1);
1379 sym->s_name = s;
1380 sym->s_block_level = 1;
1381 dl = dcs;
1382 while (dl->d_enclosing != NULL &&
1383 dl->d_enclosing->d_enclosing != NULL)
1384 dl = dl->d_enclosing;
1385 lint_assert(dl->d_kind == DLK_AUTO);
1386 } else {
1387 sym = block_zero_alloc(sizeof(*sym), "sym");
1388 sym->s_name = sb->sb_name;
1389 sym->s_block_level = block_level;
1390 dl = dcs;
1391 }
1392
1393 sym->s_def_pos = unique_curr_pos();
1394 if ((sym->s_kind = sym_kind) != SK_LABEL)
1395 sym->s_type = gettyp(INT);
1396
1397 set_sym_kind(SK_VCFT);
1398
1399 if (!in_gcc_attribute) {
1400 debug_printf("%s: symtab_add ", __func__);
1401 debug_sym("", sym, "\n");
1402 symtab_add(sym);
1403
1404 *dl->d_last_dlsym = sym;
1405 dl->d_last_dlsym = &sym->s_level_next;
1406 }
1407
1408 free(sb);
1409 return sym;
1410 }
1411
1412 /*
1413 * Construct a temporary symbol. The symbol name starts with a digit to avoid
1414 * name clashes with other identifiers.
1415 */
1416 sym_t *
1417 mktempsym(type_t *tp)
1418 {
1419 static unsigned n = 0;
1420 char *s = level_zero_alloc((size_t)block_level, 64, "string");
1421 sym_t *sym = block_zero_alloc(sizeof(*sym), "sym");
1422 scl_t scl;
1423
1424 (void)snprintf(s, 64, "%.8u_tmp", n++);
1425
1426 scl = dcs->d_scl;
1427 if (scl == NO_SCL)
1428 scl = block_level > 0 ? AUTO : EXTERN;
1429
1430 sym->s_name = s;
1431 sym->s_type = tp;
1432 sym->s_block_level = block_level;
1433 sym->s_scl = scl;
1434 sym->s_kind = SK_VCFT;
1435 sym->s_used = true;
1436 sym->s_set = true;
1437
1438 symtab_add(sym);
1439
1440 *dcs->d_last_dlsym = sym;
1441 dcs->d_last_dlsym = &sym->s_level_next;
1442
1443 return sym;
1444 }
1445
1446 /* Remove a symbol forever from the symbol table. */
1447 void
1448 rmsym(sym_t *sym)
1449 {
1450
1451 debug_step("rmsym '%s' %s '%s'",
1452 sym->s_name, symbol_kind_name(sym->s_kind),
1453 type_name(sym->s_type));
1454 symtab_remove(sym);
1455
1456 /* avoid that the symbol will later be put back to the symbol table */
1457 sym->s_block_level = -1;
1458 }
1459
1460 /*
1461 * Remove all symbols from the symbol table that have the same level as the
1462 * given symbol.
1463 */
1464 void
1465 symtab_remove_level(sym_t *syms)
1466 {
1467
1468 if (syms != NULL)
1469 debug_step("%s %d", __func__, syms->s_block_level);
1470
1471 /* Note the use of s_level_next instead of s_symtab_next. */
1472 for (sym_t *sym = syms; sym != NULL; sym = sym->s_level_next) {
1473 if (sym->s_block_level != -1) {
1474 debug_step("%s '%s' %s '%s' %d", __func__,
1475 sym->s_name, symbol_kind_name(sym->s_kind),
1476 type_name(sym->s_type), sym->s_block_level);
1477 symtab_remove(sym);
1478 sym->s_symtab_ref = NULL;
1479 }
1480 }
1481 }
1482
1483 /* Put a symbol into the symbol table. */
1484 void
1485 inssym(int level, sym_t *sym)
1486 {
1487
1488 debug_step("%s '%s' %s '%s' %d", __func__,
1489 sym->s_name, symbol_kind_name(sym->s_kind),
1490 type_name(sym->s_type), level);
1491 sym->s_block_level = level;
1492 symtab_add(sym);
1493
1494 /*
1495 * Placing the inner symbols to the beginning of the list ensures that
1496 * these symbols are preferred over symbols from the outer blocks that
1497 * happen to have the same name.
1498 */
1499 const sym_t *next = sym->s_symtab_next;
1500 if (next != NULL)
1501 lint_assert(sym->s_block_level >= next->s_block_level);
1502 }
1503
1504 /* Called at level 0 after syntax errors. */
1505 void
1506 clean_up_after_error(void)
1507 {
1508
1509 symtab_remove_locals();
1510
1511 while (mem_block_level > 0)
1512 level_free_all(mem_block_level--);
1513 }
1514
1515 /* Create a new symbol with the same name as an existing symbol. */
1516 sym_t *
1517 pushdown(const sym_t *sym)
1518 {
1519 sym_t *nsym;
1520
1521 debug_step("pushdown '%s' %s '%s'",
1522 sym->s_name, symbol_kind_name(sym->s_kind),
1523 type_name(sym->s_type));
1524 nsym = block_zero_alloc(sizeof(*nsym), "sym");
1525 lint_assert(sym->s_block_level <= block_level);
1526 nsym->s_name = sym->s_name;
1527 nsym->s_def_pos = unique_curr_pos();
1528 nsym->s_kind = sym->s_kind;
1529 nsym->s_block_level = block_level;
1530
1531 symtab_add(nsym);
1532
1533 *dcs->d_last_dlsym = nsym;
1534 dcs->d_last_dlsym = &nsym->s_level_next;
1535
1536 return nsym;
1537 }
1538
1539 /*
1540 * Free any dynamically allocated memory referenced by
1541 * the value stack or yylval.
1542 * The type of information in yylval is described by tok.
1543 */
1544 void
1545 freeyyv(void *sp, int tok)
1546 {
1547 if (tok == T_NAME || tok == T_TYPENAME) {
1548 sbuf_t *sb = *(sbuf_t **)sp;
1549 free(sb);
1550 } else if (tok == T_CON) {
1551 val_t *val = *(val_t **)sp;
1552 free(val);
1553 } else if (tok == T_STRING) {
1554 buffer *str = *(buffer **)sp;
1555 free(str->data);
1556 free(str);
1557 }
1558 }
1559