lex.c revision 1.221 1 /* $NetBSD: lex.c,v 1.221 2024/03/02 09:32: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.221 2024/03/02 09:32: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 = 0;
215 for (const char *p = s; *p != '\0'; p++) {
216 v = (v << 4) + (unsigned char)*p;
217 v ^= v >> 28;
218 }
219 return v % (sizeof(symtab) / sizeof(symtab[0]));
220 }
221
222 static void
223 symtab_add(sym_t *sym)
224 {
225 unsigned int h = hash(sym->s_name);
226 if ((sym->s_symtab_next = symtab[h]) != NULL)
227 symtab[h]->s_symtab_ref = &sym->s_symtab_next;
228 sym->s_symtab_ref = &symtab[h];
229 symtab[h] = sym;
230 }
231
232 static sym_t *
233 symtab_search(const char *name)
234 {
235
236 unsigned int h = hash(name);
237 for (sym_t *sym = symtab[h]; sym != NULL; sym = sym->s_symtab_next) {
238 if (strcmp(sym->s_name, name) != 0)
239 continue;
240 if (sym->s_keyword != NULL ||
241 sym->s_kind == sym_kind ||
242 in_gcc_attribute)
243 return sym;
244 }
245
246 return NULL;
247 }
248
249 static void
250 symtab_remove(sym_t *sym)
251 {
252
253 if ((*sym->s_symtab_ref = sym->s_symtab_next) != NULL)
254 sym->s_symtab_next->s_symtab_ref = sym->s_symtab_ref;
255 sym->s_symtab_next = NULL;
256 }
257
258 static void
259 symtab_remove_locals(void)
260 {
261
262 for (size_t i = 0; i < sizeof(symtab) / sizeof(symtab[0]); i++) {
263 for (sym_t *sym = symtab[i]; sym != NULL; ) {
264 sym_t *next = sym->s_symtab_next;
265 if (sym->s_block_level >= 1)
266 symtab_remove(sym);
267 sym = next;
268 }
269 }
270 }
271
272 #ifdef DEBUG
273 static int
274 sym_by_name(const void *va, const void *vb)
275 {
276 const sym_t *a = *(const sym_t *const *)va;
277 const sym_t *b = *(const sym_t *const *)vb;
278
279 return strcmp(a->s_name, b->s_name);
280 }
281
282 struct syms {
283 const sym_t **items;
284 size_t len;
285 size_t cap;
286 };
287
288 static void
289 syms_add(struct syms *syms, const sym_t *sym)
290 {
291 if (syms->len >= syms->cap) {
292 syms->cap *= 2;
293 syms->items = xrealloc(syms->items,
294 syms->cap * sizeof(syms->items[0]));
295 }
296 syms->items[syms->len++] = sym;
297 }
298
299 void
300 debug_symtab(void)
301 {
302 struct syms syms = { xcalloc(64, sizeof(syms.items[0])), 0, 64 };
303
304 debug_enter();
305 for (int level = -1;; level++) {
306 bool more = false;
307 size_t n = sizeof(symtab) / sizeof(symtab[0]);
308
309 syms.len = 0;
310 for (size_t i = 0; i < n; i++) {
311 for (sym_t *sym = symtab[i]; sym != NULL;) {
312 if (sym->s_block_level == level &&
313 sym->s_keyword == NULL)
314 syms_add(&syms, sym);
315 if (sym->s_block_level > level)
316 more = true;
317 sym = sym->s_symtab_next;
318 }
319 }
320
321 if (syms.len > 0) {
322 debug_step("symbol table level %d", level);
323 debug_indent_inc();
324 qsort(syms.items, syms.len, sizeof(syms.items[0]),
325 sym_by_name);
326 for (size_t i = 0; i < syms.len; i++)
327 debug_sym("", syms.items[i], "\n");
328 debug_indent_dec();
329
330 lint_assert(level != -1);
331 }
332
333 if (!more)
334 break;
335 }
336 debug_leave();
337
338 free(syms.items);
339 }
340 #endif
341
342 static void
343 register_keyword(const struct keyword *kw, bool leading, bool trailing)
344 {
345
346 const char *name;
347 if (!leading && !trailing) {
348 name = kw->kw_name;
349 } else {
350 char buf[256];
351 (void)snprintf(buf, sizeof(buf), "%s%s%s",
352 leading ? "__" : "", kw->kw_name, trailing ? "__" : "");
353 name = xstrdup(buf);
354 }
355
356 sym_t *sym = block_zero_alloc(sizeof(*sym), "sym");
357 sym->s_name = name;
358 sym->s_keyword = kw;
359 int tok = kw->kw_token;
360 sym->u.s_keyword.sk_token = tok;
361 if (tok == T_TYPE || tok == T_STRUCT_OR_UNION)
362 sym->u.s_keyword.u.sk_tspec = kw->u.kw_tspec;
363 if (tok == T_SCLASS)
364 sym->s_scl = kw->u.kw_scl;
365 if (tok == T_QUAL)
366 sym->u.s_keyword.u.sk_type_qualifier = kw->u.kw_tqual;
367 if (tok == T_FUNCTION_SPECIFIER)
368 sym->u.s_keyword.u.function_specifier = kw->u.kw_fs;
369
370 symtab_add(sym);
371 }
372
373 static bool
374 is_keyword_known(const struct keyword *kw)
375 {
376
377 if (kw->kw_added_in_c23 && !allow_c23)
378 return false;
379 if ((kw->kw_added_in_c90 || kw->kw_added_in_c99_or_c11) && !allow_c90)
380 return false;
381
382 /*
383 * In the 1990s, GCC defined several keywords that were later
384 * incorporated into C99, therefore in GCC mode, all C99 keywords are
385 * made available. The C11 keywords are made available as well, but
386 * there are so few that they don't matter practically.
387 */
388 if (allow_gcc)
389 return true;
390 if (kw->kw_gcc)
391 return false;
392
393 if (kw->kw_added_in_c99_or_c11 && !allow_c99)
394 return false;
395 return true;
396 }
397
398 /* Write all keywords to the symbol table. */
399 void
400 init_lex(void)
401 {
402
403 size_t n = sizeof(keywords) / sizeof(keywords[0]);
404 for (size_t i = 0; i < n; i++) {
405 const struct keyword *kw = keywords + i;
406 if (!is_keyword_known(kw))
407 continue;
408 if (kw->kw_plain)
409 register_keyword(kw, false, false);
410 if (kw->kw_leading)
411 register_keyword(kw, true, false);
412 if (kw->kw_both)
413 register_keyword(kw, true, true);
414 }
415 }
416
417 /*
418 * When scanning the remainder of a long token (see lex_input), read a byte
419 * and return it as an unsigned char or as EOF.
420 *
421 * Increment the line counts if necessary.
422 */
423 static int
424 read_byte(void)
425 {
426 int c = lex_input();
427
428 if (c == '\n')
429 lex_next_line();
430 return c == '\0' ? EOF : c; /* lex returns 0 on EOF. */
431 }
432
433 static int
434 lex_keyword(sym_t *sym)
435 {
436 int tok = sym->u.s_keyword.sk_token;
437
438 if (tok == T_SCLASS)
439 yylval.y_scl = sym->s_scl;
440 if (tok == T_TYPE || tok == T_STRUCT_OR_UNION)
441 yylval.y_tspec = sym->u.s_keyword.u.sk_tspec;
442 if (tok == T_QUAL)
443 yylval.y_type_qualifiers =
444 sym->u.s_keyword.u.sk_type_qualifier;
445 if (tok == T_FUNCTION_SPECIFIER)
446 yylval.y_function_specifier =
447 sym->u.s_keyword.u.function_specifier;
448 return tok;
449 }
450
451 /*
452 * Look up the definition of a name in the symbol table. This symbol must
453 * either be a keyword or a symbol of the type required by sym_kind (label,
454 * member, tag, ...).
455 */
456 extern int
457 lex_name(const char *yytext, size_t yyleng)
458 {
459
460 sym_t *sym = symtab_search(yytext);
461 if (sym != NULL && sym->s_keyword != NULL)
462 return lex_keyword(sym);
463
464 sbuf_t *sb = xmalloc(sizeof(*sb));
465 sb->sb_len = yyleng;
466 sb->sb_sym = sym;
467 yylval.y_name = sb;
468
469 if (sym != NULL) {
470 lint_assert(block_level >= sym->s_block_level);
471 sb->sb_name = sym->s_name;
472 return sym->s_scl == TYPEDEF ? T_TYPENAME : T_NAME;
473 }
474
475 char *name = block_zero_alloc(yyleng + 1, "string");
476 (void)memcpy(name, yytext, yyleng + 1);
477 sb->sb_name = name;
478 return T_NAME;
479 }
480
481 // Determines whether the constant is signed in traditional C but unsigned in
482 // C90 and later.
483 static bool
484 is_unsigned_since_c90(unsigned ls, uint64_t ui, int base)
485 {
486 if (ui <= TARG_INT_MAX)
487 return false;
488 if (ls == 0 && ui <= TARG_UINT_MAX && base != 10)
489 return true;
490 return ls <= 1 && ui > TARG_LONG_MAX;
491 }
492
493 static tspec_t
494 integer_constant_type_signed(unsigned ls, uint64_t ui, int base, bool warned)
495 {
496 if (ls == 0 && ui <= TARG_INT_MAX)
497 return INT;
498 if (ls == 0 && ui <= TARG_UINT_MAX && base != 10 && allow_c90)
499 return UINT;
500 if (ls == 0 && ui <= TARG_LONG_MAX)
501 return LONG;
502
503 if (ls <= 1 && ui <= TARG_LONG_MAX)
504 return LONG;
505 if (ls <= 1 && ui <= TARG_ULONG_MAX && base != 10)
506 return allow_c90 ? ULONG : LONG;
507 if (ls <= 1 && !allow_c99) {
508 if (!warned)
509 /* integer constant out of range */
510 warning(252);
511 return allow_c90 ? ULONG : LONG;
512 }
513
514 if (ui <= TARG_LLONG_MAX)
515 return LLONG;
516 if (ui <= TARG_ULLONG_MAX && base != 10)
517 return allow_c90 ? ULLONG : LLONG;
518 if (!warned)
519 /* integer constant out of range */
520 warning(252);
521 return allow_c90 ? ULLONG : LLONG;
522 }
523
524 static tspec_t
525 integer_constant_type_unsigned(unsigned l, uint64_t ui, bool warned)
526 {
527 if (l == 0 && ui <= TARG_UINT_MAX)
528 return UINT;
529
530 if (l <= 1 && ui <= TARG_ULONG_MAX)
531 return ULONG;
532 if (l <= 1 && !allow_c99) {
533 if (!warned)
534 /* integer constant out of range */
535 warning(252);
536 return ULONG;
537 }
538
539 if (ui <= TARG_ULLONG_MAX)
540 return ULLONG;
541 if (!warned)
542 /* integer constant out of range */
543 warning(252);
544 return ULLONG;
545 }
546
547 int
548 lex_integer_constant(const char *yytext, size_t yyleng, int base)
549 {
550 const char *cp = yytext;
551 size_t len = yyleng;
552
553 /* skip 0[xX] or 0[bB] */
554 if (base == 16 || base == 2) {
555 cp += 2;
556 len -= 2;
557 }
558
559 /* read suffixes */
560 unsigned l_suffix = 0, u_suffix = 0;
561 for (;; len--) {
562 char c = cp[len - 1];
563 if (c == 'l' || c == 'L')
564 l_suffix++;
565 else if (c == 'u' || c == 'U')
566 u_suffix++;
567 else
568 break;
569 }
570 if (l_suffix > 2 || u_suffix > 1) {
571 /* malformed integer constant */
572 warning(251);
573 if (l_suffix > 2)
574 l_suffix = 2;
575 if (u_suffix > 1)
576 u_suffix = 1;
577 }
578 if (!allow_c90 && u_suffix > 0)
579 /* suffix 'U' is illegal in traditional C */
580 warning(97);
581
582 bool warned = false;
583 errno = 0;
584 char *eptr;
585 uint64_t ui = (uint64_t)strtoull(cp, &eptr, base);
586 lint_assert(eptr == cp + len);
587 if (errno != 0) {
588 /* integer constant out of range */
589 warning(252);
590 warned = true;
591 }
592
593 if (any_query_enabled && base == 8 && ui != 0)
594 /* octal number '%.*s' */
595 query_message(8, (int)len, cp);
596
597 bool unsigned_since_c90 = allow_trad && allow_c90 && u_suffix == 0
598 && is_unsigned_since_c90(l_suffix, ui, base);
599
600 tspec_t t = u_suffix > 0
601 ? integer_constant_type_unsigned(l_suffix, ui, warned)
602 : integer_constant_type_signed(l_suffix, ui, base, warned);
603 ui = (uint64_t)convert_integer((int64_t)ui, t, 0);
604
605 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
606 yylval.y_val->v_tspec = t;
607 yylval.y_val->v_unsigned_since_c90 = unsigned_since_c90;
608 yylval.y_val->u.integer = (int64_t)ui;
609
610 return T_CON;
611 }
612
613 /*
614 * Extend or truncate si to match t. If t is signed, sign-extend.
615 *
616 * len is the number of significant bits. If len is 0, len is set
617 * to the width of type t.
618 */
619 int64_t
620 convert_integer(int64_t si, tspec_t t, unsigned int len)
621 {
622
623 if (len == 0)
624 len = size_in_bits(t);
625
626 uint64_t vbits = value_bits(len);
627 uint64_t ui = (uint64_t)si;
628 return t == PTR || is_uinteger(t) || ((ui & bit(len - 1)) == 0)
629 ? (int64_t)(ui & vbits)
630 : (int64_t)(ui | ~vbits);
631 }
632
633 int
634 lex_floating_constant(const char *yytext, size_t yyleng)
635 {
636 const char *cp = yytext;
637 size_t len = yyleng;
638
639 bool imaginary = cp[len - 1] == 'i';
640 if (imaginary)
641 len--;
642
643 char c = cp[len - 1];
644 tspec_t t;
645 if (c == 'f' || c == 'F') {
646 t = imaginary ? FCOMPLEX : FLOAT;
647 len--;
648 } else if (c == 'l' || c == 'L') {
649 t = imaginary ? LCOMPLEX : LDOUBLE;
650 len--;
651 } else
652 t = imaginary ? DCOMPLEX : DOUBLE;
653
654 if (!allow_c90 && t != DOUBLE)
655 /* suffixes 'F' and 'L' are illegal in traditional C */
656 warning(98);
657
658 errno = 0;
659 char *eptr;
660 long double ld = strtold(cp, &eptr);
661 lint_assert(eptr == cp + len);
662 if (errno != 0)
663 /* floating-point constant out of range */
664 warning(248);
665 else if (t == FLOAT) {
666 ld = (float)ld;
667 if (isfinite(ld) == 0) {
668 /* floating-point constant out of range */
669 warning(248);
670 ld = ld > 0 ? FLT_MAX : -FLT_MAX;
671 }
672 } else if (t == DOUBLE
673 || /* CONSTCOND */ LDOUBLE_SIZE == DOUBLE_SIZE) {
674 ld = (double)ld;
675 if (isfinite(ld) == 0) {
676 /* floating-point constant out of range */
677 warning(248);
678 ld = ld > 0 ? DBL_MAX : -DBL_MAX;
679 }
680 }
681
682 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
683 yylval.y_val->v_tspec = t;
684 yylval.y_val->u.floating = ld;
685
686 return T_CON;
687 }
688
689 int
690 lex_operator(int t, op_t o)
691 {
692
693 yylval.y_op = o;
694 return t;
695 }
696
697 static buffer *
698 read_quoted(bool *complete, char delim, bool wide)
699 {
700 buffer *buf = xcalloc(1, sizeof(*buf));
701 buf_init(buf);
702 if (wide)
703 buf_add_char(buf, 'L');
704 buf_add_char(buf, delim);
705
706 for (;;) {
707 int c = read_byte();
708 if (c <= 0)
709 break;
710 buf_add_char(buf, (char)c);
711 if (c == '\n')
712 break;
713 if (c == delim) {
714 *complete = true;
715 return buf;
716 }
717 if (c == '\\') {
718 c = read_byte();
719 buf_add_char(buf, (char)(c <= 0 ? ' ' : c));
720 if (c <= 0)
721 break;
722 }
723 }
724 *complete = false;
725 buf_add_char(buf, delim);
726 return buf;
727 }
728
729 bool
730 quoted_next(const buffer *lit, quoted_iterator *it)
731 {
732 const char *s = lit->data;
733 size_t len = lit->len;
734
735 *it = (quoted_iterator){ .i = it->i, .start = it->i };
736
737 char delim = s[s[0] == 'L' ? 1 : 0];
738
739 bool in_the_middle = it->i > 0;
740 if (it->i == 0) {
741 it->start = s[0] == 'L' ? 2 : 1;
742 it->i = it->start;
743 }
744
745 for (;;) {
746 if (s[it->i] != delim)
747 break;
748 if (it->i + 1 == len)
749 return false;
750 it->next_literal = in_the_middle;
751 it->start += 2;
752 it->i += 2;
753 }
754
755 again:
756 switch (s[it->i]) {
757 case '\\':
758 it->i++;
759 goto backslash;
760 case '\n':
761 it->unescaped_newline = true;
762 return false;
763 default:
764 it->value = (unsigned char)s[it->i++];
765 return true;
766 }
767
768 backslash:
769 it->escaped = true;
770 if ('0' <= s[it->i] && s[it->i] <= '7')
771 goto octal_escape;
772 switch (s[it->i++]) {
773 case '\n':
774 goto again;
775 case 'a':
776 it->named_escape = true;
777 it->value = '\a';
778 it->invalid_escape = !allow_c90;
779 return true;
780 case 'b':
781 it->named_escape = true;
782 it->value = '\b';
783 return true;
784 case 'e':
785 it->named_escape = true;
786 it->value = '\033';
787 it->invalid_escape = !allow_gcc;
788 return true;
789 case 'f':
790 it->named_escape = true;
791 it->value = '\f';
792 return true;
793 case 'n':
794 it->named_escape = true;
795 it->value = '\n';
796 return true;
797 case 'r':
798 it->named_escape = true;
799 it->value = '\r';
800 return true;
801 case 't':
802 it->named_escape = true;
803 it->value = '\t';
804 return true;
805 case 'v':
806 it->named_escape = true;
807 it->value = '\v';
808 it->invalid_escape = !allow_c90;
809 return true;
810 case 'x':
811 goto hex_escape;
812 case '"':
813 it->literal_escape = true;
814 it->value = '"';
815 it->invalid_escape = !allow_c90 && delim == '\'';
816 return true;
817 case '?':
818 it->literal_escape = true;
819 it->value = '?';
820 it->invalid_escape = !allow_c90;
821 return true;
822 default:
823 it->invalid_escape = true;
824 /* FALLTHROUGH */
825 case '\'':
826 case '\\':
827 it->literal_escape = true;
828 it->value = (unsigned char)s[it->i - 1];
829 return true;
830 }
831
832 octal_escape:
833 it->octal_digits++;
834 it->value = s[it->i++] - '0';
835 if ('0' <= s[it->i] && s[it->i] <= '7') {
836 it->octal_digits++;
837 it->value = 8 * it->value + (s[it->i++] - '0');
838 if ('0' <= s[it->i] && s[it->i] <= '7') {
839 it->octal_digits++;
840 it->value = 8 * it->value + (s[it->i++] - '0');
841 it->overflow = it->value > TARG_UCHAR_MAX
842 && s[0] != 'L';
843 }
844 }
845 return true;
846
847 hex_escape:
848 for (;;) {
849 char ch = s[it->i];
850 unsigned digit_value;
851 if ('0' <= ch && ch <= '9')
852 digit_value = ch - '0';
853 else if ('A' <= ch && ch <= 'F')
854 digit_value = 10 + (ch - 'A');
855 else if ('a' <= ch && ch <= 'f')
856 digit_value = 10 + (ch - 'a');
857 else
858 break;
859
860 it->i++;
861 it->value = 16 * it->value + digit_value;
862 uint64_t limit = s[0] == 'L' ? TARG_UINT_MAX : TARG_UCHAR_MAX;
863 if (it->value > limit)
864 it->overflow = true;
865 if (it->hex_digits < 3)
866 it->hex_digits++;
867 }
868 it->missing_hex_digits = it->hex_digits == 0;
869 return true;
870 }
871
872 static void
873 check_quoted(const buffer *buf, bool complete, char delim)
874 {
875 quoted_iterator it = { .i = 0 }, prev = it;
876 for (; quoted_next(buf, &it); prev = it) {
877 if (it.missing_hex_digits)
878 /* no hex digits follow \x */
879 error(74);
880 if (it.hex_digits > 0 && !allow_c90)
881 /* \x undefined in traditional C */
882 warning(82);
883 else if (!it.invalid_escape)
884 ;
885 else if (it.value == '8' || it.value == '9')
886 /* bad octal digit '%c' */
887 warning(77, (int)it.value);
888 else if (it.literal_escape && it.value == '?')
889 /* \? undefined in traditional C */
890 warning(263);
891 else if (it.literal_escape && it.value == '"')
892 /* \" inside character constants undefined in ... */
893 warning(262);
894 else if (it.named_escape && it.value == '\a')
895 /* \a undefined in traditional C */
896 warning(81);
897 else if (it.named_escape && it.value == '\v')
898 /* \v undefined in traditional C */
899 warning(264);
900 else {
901 unsigned char ch = buf->data[it.i - 1];
902 if (isprint(ch))
903 /* dubious escape \%c */
904 warning(79, ch);
905 else
906 /* dubious escape \%o */
907 warning(80, ch);
908 }
909 if (it.overflow && it.hex_digits > 0)
910 /* overflow in hex escape */
911 warning(75);
912 if (it.overflow && it.octal_digits > 0)
913 /* character escape does not fit in character */
914 warning(76);
915 if (it.value < ' ' && !it.escaped && complete)
916 /* invisible character U+%04X in %s */
917 query_message(17, (unsigned)it.value, delim == '"'
918 ? "string literal" : "character constant");
919 if (prev.octal_digits > 0 && prev.octal_digits < 3
920 && !it.escaped && it.value >= '8' && it.value <= '9')
921 /* short octal escape '%.*s' followed by digit '%c' */
922 warning(356, (int)(prev.i - prev.start),
923 buf->data + prev.start, buf->data[it.start]);
924 }
925 if (it.unescaped_newline)
926 /* newline in string or char constant */
927 error(254);
928 if (!complete && delim == '"')
929 /* unterminated string constant */
930 error(258);
931 if (!complete && delim == '\'')
932 /* unterminated character constant */
933 error(253);
934 }
935
936 static buffer *
937 lex_quoted(char delim, bool wide)
938 {
939 bool complete;
940 buffer *buf = read_quoted(&complete, delim, wide);
941 check_quoted(buf, complete, delim);
942 return buf;
943 }
944
945 /* Called if lex found a leading "'". */
946 int
947 lex_character_constant(void)
948 {
949 buffer *buf = lex_quoted('\'', false);
950
951 size_t n = 0;
952 uint64_t val = 0;
953 quoted_iterator it = { .i = 0 };
954 while (quoted_next(buf, &it)) {
955 val = (val << CHAR_SIZE) + it.value;
956 n++;
957 }
958 if (n > sizeof(int) || (n > 1 && (pflag || hflag))) {
959 /*
960 * XXX: ^^ should rather be sizeof(TARG_INT). Luckily,
961 * sizeof(int) is the same on all supported platforms.
962 */
963 /* too many characters in character constant */
964 error(71);
965 } else if (n > 1)
966 /* multi-character character constant */
967 warning(294);
968 else if (n == 0 && !it.unescaped_newline)
969 /* empty character constant */
970 error(73);
971
972 int64_t cval = n == 1
973 ? convert_integer((int64_t)val, CHAR, CHAR_SIZE)
974 : (int64_t)val;
975
976 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
977 yylval.y_val->v_tspec = INT;
978 yylval.y_val->v_char_constant = true;
979 yylval.y_val->u.integer = cval;
980
981 return T_CON;
982 }
983
984 /*
985 * Called if lex found a leading L\'
986 */
987 int
988 lex_wide_character_constant(void)
989 {
990 buffer *buf = lex_quoted('\'', true);
991
992 static char wbuf[MB_LEN_MAX + 1];
993 size_t n = 0, nmax = MB_CUR_MAX;
994
995 quoted_iterator it = { .i = 0 };
996 while (quoted_next(buf, &it)) {
997 if (n < nmax)
998 wbuf[n] = (char)it.value;
999 n++;
1000 }
1001
1002 wchar_t wc = 0;
1003 if (n == 0)
1004 /* empty character constant */
1005 error(73);
1006 else if (n > nmax) {
1007 n = nmax;
1008 /* too many characters in character constant */
1009 error(71);
1010 } else {
1011 wbuf[n] = '\0';
1012 (void)mbtowc(NULL, NULL, 0);
1013 if (mbtowc(&wc, wbuf, nmax) < 0)
1014 /* invalid multibyte character */
1015 error(291);
1016 }
1017
1018 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
1019 yylval.y_val->v_tspec = WCHAR_TSPEC;
1020 yylval.y_val->v_char_constant = true;
1021 yylval.y_val->u.integer = wc;
1022
1023 return T_CON;
1024 }
1025
1026 /* See https://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html */
1027 static void
1028 parse_line_directive_flags(const char *p,
1029 bool *is_begin, bool *is_end, bool *is_system)
1030 {
1031
1032 *is_begin = false;
1033 *is_end = false;
1034 *is_system = false;
1035
1036 while (*p != '\0') {
1037 while (isspace((unsigned char)*p))
1038 p++;
1039
1040 const char *word = p;
1041 while (*p != '\0' && !isspace((unsigned char)*p))
1042 p++;
1043 size_t len = (size_t)(p - word);
1044
1045 if (len == 1 && word[0] == '1')
1046 *is_begin = true;
1047 if (len == 1 && word[0] == '2')
1048 *is_end = true;
1049 if (len == 1 && word[0] == '3')
1050 *is_system = true;
1051 /* Flag '4' is only interesting for C++. */
1052 }
1053 }
1054
1055 /*
1056 * The first directive of the preprocessed translation unit provides the name
1057 * of the C source file as specified at the command line.
1058 */
1059 static void
1060 set_csrc_pos(void)
1061 {
1062 static bool done;
1063
1064 if (done)
1065 return;
1066 done = true;
1067 csrc_pos.p_file = curr_pos.p_file;
1068 outsrc(transform_filename(curr_pos.p_file, strlen(curr_pos.p_file)));
1069 }
1070
1071 /*
1072 * Called for preprocessor directives. Currently implemented are:
1073 * # pragma [argument...]
1074 * # lineno
1075 * # lineno "filename" [GCC-flag...]
1076 */
1077 void
1078 lex_directive(const char *yytext)
1079 {
1080 const char *p = yytext + 1; /* skip '#' */
1081
1082 while (*p == ' ' || *p == '\t')
1083 p++;
1084
1085 if (!isdigit((unsigned char)*p)) {
1086 if (strncmp(p, "pragma", 6) == 0
1087 && isspace((unsigned char)p[6]))
1088 return;
1089 goto error;
1090 }
1091
1092 char *end;
1093 long ln = strtol(--p, &end, 10);
1094 if (end == p)
1095 goto error;
1096 p = end;
1097
1098 if (*p != ' ' && *p != '\t' && *p != '\0')
1099 goto error;
1100 while (*p == ' ' || *p == '\t')
1101 p++;
1102
1103 if (*p != '\0') {
1104 if (*p != '"')
1105 goto error;
1106 const char *fn = ++p;
1107 while (*p != '"' && *p != '\0')
1108 p++;
1109 if (*p != '"')
1110 goto error;
1111 size_t fn_len = p++ - fn;
1112 if (fn_len > PATH_MAX)
1113 goto error;
1114 if (fn_len == 0) {
1115 fn = "{standard input}";
1116 fn_len = strlen(fn);
1117 }
1118 curr_pos.p_file = record_filename(fn, fn_len);
1119 set_csrc_pos();
1120
1121 bool is_begin, is_end, is_system;
1122 parse_line_directive_flags(p, &is_begin, &is_end, &is_system);
1123 update_location(curr_pos.p_file, (int)ln, is_begin, is_end);
1124 in_system_header = is_system;
1125 }
1126 curr_pos.p_line = (int)ln - 1;
1127 curr_pos.p_uniq = 0;
1128 if (curr_pos.p_file == csrc_pos.p_file) {
1129 csrc_pos.p_line = (int)ln - 1;
1130 csrc_pos.p_uniq = 0;
1131 }
1132 return;
1133
1134 error:
1135 /* undefined or invalid '#' directive */
1136 warning(255);
1137 }
1138
1139 /* Handle lint comments such as ARGSUSED. */
1140 void
1141 lex_comment(void)
1142 {
1143 int c;
1144 static const struct {
1145 const char name[18];
1146 bool arg;
1147 lint_comment comment;
1148 } keywtab[] = {
1149 { "ARGSUSED", true, LC_ARGSUSED },
1150 { "BITFIELDTYPE", false, LC_BITFIELDTYPE },
1151 { "CONSTCOND", false, LC_CONSTCOND },
1152 { "CONSTANTCOND", false, LC_CONSTCOND },
1153 { "CONSTANTCONDITION", false, LC_CONSTCOND },
1154 { "FALLTHRU", false, LC_FALLTHROUGH },
1155 { "FALLTHROUGH", false, LC_FALLTHROUGH },
1156 { "FALL THROUGH", false, LC_FALLTHROUGH },
1157 { "fallthrough", false, LC_FALLTHROUGH },
1158 { "LINTLIBRARY", false, LC_LINTLIBRARY },
1159 { "LINTED", true, LC_LINTED },
1160 { "LONGLONG", false, LC_LONGLONG },
1161 { "NOSTRICT", true, LC_LINTED },
1162 { "NOTREACHED", false, LC_NOTREACHED },
1163 { "PRINTFLIKE", true, LC_PRINTFLIKE },
1164 { "PROTOLIB", true, LC_PROTOLIB },
1165 { "SCANFLIKE", true, LC_SCANFLIKE },
1166 { "VARARGS", true, LC_VARARGS },
1167 };
1168 char keywd[32];
1169 char arg[32];
1170 size_t l, i;
1171 int a;
1172
1173 bool seen_end_of_comment = false;
1174
1175 while (c = read_byte(), isspace(c))
1176 continue;
1177
1178 /* Read the potential keyword to keywd */
1179 l = 0;
1180 while (c != EOF && l < sizeof(keywd) - 1 &&
1181 (isalpha(c) || isspace(c))) {
1182 if (islower(c) && l > 0 && isupper((unsigned char)keywd[0]))
1183 break;
1184 keywd[l++] = (char)c;
1185 c = read_byte();
1186 }
1187 while (l > 0 && isspace((unsigned char)keywd[l - 1]))
1188 l--;
1189 keywd[l] = '\0';
1190
1191 /* look for the keyword */
1192 for (i = 0; i < sizeof(keywtab) / sizeof(keywtab[0]); i++)
1193 if (strcmp(keywtab[i].name, keywd) == 0)
1194 goto found_keyword;
1195 goto skip_rest;
1196
1197 found_keyword:
1198 while (isspace(c))
1199 c = read_byte();
1200
1201 /* read the argument, if the keyword accepts one and there is one */
1202 l = 0;
1203 if (keywtab[i].arg) {
1204 while (isdigit(c) && l < sizeof(arg) - 1) {
1205 arg[l++] = (char)c;
1206 c = read_byte();
1207 }
1208 }
1209 arg[l] = '\0';
1210 a = l != 0 ? atoi(arg) : -1;
1211
1212 while (isspace(c))
1213 c = read_byte();
1214
1215 seen_end_of_comment = c == '*' && (c = read_byte()) == '/';
1216 if (!seen_end_of_comment && keywtab[i].comment != LC_LINTED)
1217 /* extra characters in lint comment */
1218 warning(257);
1219
1220 handle_lint_comment(keywtab[i].comment, a);
1221
1222 skip_rest:
1223 while (!seen_end_of_comment) {
1224 int lc = c;
1225 if ((c = read_byte()) == EOF) {
1226 /* unterminated comment */
1227 error(256);
1228 break;
1229 }
1230 if (lc == '*' && c == '/')
1231 seen_end_of_comment = true;
1232 }
1233 }
1234
1235 void
1236 lex_slash_slash_comment(void)
1237 {
1238 int c;
1239
1240 if (!allow_c99 && !allow_gcc)
1241 /* %s does not support '//' comments */
1242 gnuism(312, allow_c90 ? "C90" : "traditional C");
1243
1244 while ((c = read_byte()) != EOF && c != '\n')
1245 continue;
1246 }
1247
1248 /*
1249 * Clear flags for lint comments LINTED, LONGLONG and CONSTCOND.
1250 * clear_warn_flags is called after function definitions and global and
1251 * local declarations and definitions. It is also called between
1252 * the controlling expression and the body of control statements
1253 * (if, switch, for, while).
1254 */
1255 void
1256 clear_warn_flags(void)
1257 {
1258
1259 lwarn = LWARN_ALL;
1260 suppress_longlong = false;
1261 suppress_constcond = false;
1262 }
1263
1264 int
1265 lex_string(void)
1266 {
1267 yylval.y_string = lex_quoted('"', false);
1268 return T_STRING;
1269 }
1270
1271 static size_t
1272 wide_length(const buffer *buf)
1273 {
1274
1275 (void)mblen(NULL, 0);
1276 size_t len = 0, i = 0;
1277 while (i < buf->len) {
1278 int n = mblen(buf->data + i, MB_CUR_MAX);
1279 if (n == -1) {
1280 /* invalid multibyte character */
1281 error(291);
1282 break;
1283 }
1284 i += n > 1 ? n : 1;
1285 len++;
1286 }
1287 return len;
1288 }
1289
1290 int
1291 lex_wide_string(void)
1292 {
1293 buffer *buf = lex_quoted('"', true);
1294
1295 buffer str;
1296 buf_init(&str);
1297 quoted_iterator it = { .i = 0 };
1298 while (quoted_next(buf, &it))
1299 buf_add_char(&str, (char)it.value);
1300
1301 free(buf->data);
1302 *buf = (buffer) { .len = wide_length(&str) };
1303
1304 yylval.y_string = buf;
1305 return T_STRING;
1306 }
1307
1308 void
1309 lex_next_line(void)
1310 {
1311 curr_pos.p_line++;
1312 curr_pos.p_uniq = 0;
1313 debug_skip_indent();
1314 debug_printf("parsing %s:%d\n", curr_pos.p_file, curr_pos.p_line);
1315 if (curr_pos.p_file == csrc_pos.p_file) {
1316 csrc_pos.p_line++;
1317 csrc_pos.p_uniq = 0;
1318 }
1319 }
1320
1321 void
1322 lex_unknown_character(int c)
1323 {
1324
1325 /* unknown character \%o */
1326 error(250, c);
1327 }
1328
1329 /*
1330 * The scanner does not create new symbol table entries for symbols it cannot
1331 * find in the symbol table. This is to avoid putting undeclared symbols into
1332 * the symbol table if a syntax error occurs.
1333 *
1334 * getsym is called as soon as it is probably ok to put the symbol in the
1335 * symbol table. It is still possible that symbols are put in the symbol
1336 * table that are not completely declared due to syntax errors. To avoid too
1337 * many problems in this case, symbols get type 'int' in getsym.
1338 *
1339 * XXX calls to getsym should be delayed until declare_1_* is called.
1340 */
1341 sym_t *
1342 getsym(sbuf_t *sb)
1343 {
1344
1345 sym_t *sym = sb->sb_sym;
1346
1347 /*
1348 * During member declaration it is possible that name() looked for
1349 * symbols of type SK_VCFT, although it should have looked for symbols
1350 * of type SK_TAG. Same can happen for labels. Both cases are
1351 * compensated here.
1352 */
1353 if (sym_kind == SK_MEMBER || sym_kind == SK_LABEL) {
1354 if (sym == NULL || sym->s_kind == SK_VCFT)
1355 sym = symtab_search(sb->sb_name);
1356 }
1357
1358 if (sym != NULL) {
1359 lint_assert(sym->s_kind == sym_kind);
1360 set_sym_kind(SK_VCFT);
1361 free(sb);
1362 return sym;
1363 }
1364
1365 /* create a new symbol table entry */
1366
1367 /* labels must always be allocated at level 1 (outermost block) */
1368 decl_level *dl;
1369 if (sym_kind == SK_LABEL) {
1370 sym = level_zero_alloc(1, sizeof(*sym), "sym");
1371 char *s = level_zero_alloc(1, sb->sb_len + 1, "string");
1372 (void)memcpy(s, sb->sb_name, sb->sb_len + 1);
1373 sym->s_name = s;
1374 sym->s_block_level = 1;
1375 dl = dcs;
1376 while (dl->d_enclosing != NULL &&
1377 dl->d_enclosing->d_enclosing != NULL)
1378 dl = dl->d_enclosing;
1379 lint_assert(dl->d_kind == DLK_AUTO);
1380 } else {
1381 sym = block_zero_alloc(sizeof(*sym), "sym");
1382 sym->s_name = sb->sb_name;
1383 sym->s_block_level = block_level;
1384 dl = dcs;
1385 }
1386
1387 sym->s_def_pos = unique_curr_pos();
1388 if ((sym->s_kind = sym_kind) != SK_LABEL)
1389 sym->s_type = gettyp(INT);
1390
1391 set_sym_kind(SK_VCFT);
1392
1393 if (!in_gcc_attribute) {
1394 debug_printf("%s: symtab_add ", __func__);
1395 debug_sym("", sym, "\n");
1396 symtab_add(sym);
1397
1398 *dl->d_last_dlsym = sym;
1399 dl->d_last_dlsym = &sym->s_level_next;
1400 }
1401
1402 free(sb);
1403 return sym;
1404 }
1405
1406 /*
1407 * Construct a temporary symbol. The symbol name starts with a digit to avoid
1408 * name clashes with other identifiers.
1409 */
1410 sym_t *
1411 mktempsym(type_t *tp)
1412 {
1413 static unsigned n = 0;
1414 char *s = level_zero_alloc((size_t)block_level, 64, "string");
1415 sym_t *sym = block_zero_alloc(sizeof(*sym), "sym");
1416 scl_t scl;
1417
1418 (void)snprintf(s, 64, "%.8u_tmp", n++);
1419
1420 scl = dcs->d_scl;
1421 if (scl == NO_SCL)
1422 scl = block_level > 0 ? AUTO : EXTERN;
1423
1424 sym->s_name = s;
1425 sym->s_type = tp;
1426 sym->s_block_level = block_level;
1427 sym->s_scl = scl;
1428 sym->s_kind = SK_VCFT;
1429 sym->s_used = true;
1430 sym->s_set = true;
1431
1432 symtab_add(sym);
1433
1434 *dcs->d_last_dlsym = sym;
1435 dcs->d_last_dlsym = &sym->s_level_next;
1436
1437 return sym;
1438 }
1439
1440 /* Remove a symbol forever from the symbol table. */
1441 void
1442 rmsym(sym_t *sym)
1443 {
1444
1445 debug_step("rmsym '%s' %s '%s'",
1446 sym->s_name, symbol_kind_name(sym->s_kind),
1447 type_name(sym->s_type));
1448 symtab_remove(sym);
1449
1450 /* avoid that the symbol will later be put back to the symbol table */
1451 sym->s_block_level = -1;
1452 }
1453
1454 /*
1455 * Remove all symbols from the symbol table that have the same level as the
1456 * given symbol.
1457 */
1458 void
1459 symtab_remove_level(sym_t *syms)
1460 {
1461
1462 if (syms != NULL)
1463 debug_step("%s %d", __func__, syms->s_block_level);
1464
1465 /* Note the use of s_level_next instead of s_symtab_next. */
1466 for (sym_t *sym = syms; sym != NULL; sym = sym->s_level_next) {
1467 if (sym->s_block_level != -1) {
1468 debug_step("%s '%s' %s '%s' %d", __func__,
1469 sym->s_name, symbol_kind_name(sym->s_kind),
1470 type_name(sym->s_type), sym->s_block_level);
1471 symtab_remove(sym);
1472 sym->s_symtab_ref = NULL;
1473 }
1474 }
1475 }
1476
1477 /* Put a symbol into the symbol table. */
1478 void
1479 inssym(int level, sym_t *sym)
1480 {
1481
1482 debug_step("%s '%s' %s '%s' %d", __func__,
1483 sym->s_name, symbol_kind_name(sym->s_kind),
1484 type_name(sym->s_type), level);
1485 sym->s_block_level = level;
1486 symtab_add(sym);
1487
1488 /*
1489 * Placing the inner symbols to the beginning of the list ensures that
1490 * these symbols are preferred over symbols from the outer blocks that
1491 * happen to have the same name.
1492 */
1493 const sym_t *next = sym->s_symtab_next;
1494 if (next != NULL)
1495 lint_assert(sym->s_block_level >= next->s_block_level);
1496 }
1497
1498 /* Called at level 0 after syntax errors. */
1499 void
1500 clean_up_after_error(void)
1501 {
1502
1503 symtab_remove_locals();
1504
1505 while (mem_block_level > 0)
1506 level_free_all(mem_block_level--);
1507 }
1508
1509 /* Create a new symbol with the same name as an existing symbol. */
1510 sym_t *
1511 pushdown(const sym_t *sym)
1512 {
1513 sym_t *nsym;
1514
1515 debug_step("pushdown '%s' %s '%s'",
1516 sym->s_name, symbol_kind_name(sym->s_kind),
1517 type_name(sym->s_type));
1518 nsym = block_zero_alloc(sizeof(*nsym), "sym");
1519 lint_assert(sym->s_block_level <= block_level);
1520 nsym->s_name = sym->s_name;
1521 nsym->s_def_pos = unique_curr_pos();
1522 nsym->s_kind = sym->s_kind;
1523 nsym->s_block_level = block_level;
1524
1525 symtab_add(nsym);
1526
1527 *dcs->d_last_dlsym = nsym;
1528 dcs->d_last_dlsym = &nsym->s_level_next;
1529
1530 return nsym;
1531 }
1532
1533 /*
1534 * Free any dynamically allocated memory referenced by
1535 * the value stack or yylval.
1536 * The type of information in yylval is described by tok.
1537 */
1538 void
1539 freeyyv(void *sp, int tok)
1540 {
1541 if (tok == T_NAME || tok == T_TYPENAME) {
1542 sbuf_t *sb = *(sbuf_t **)sp;
1543 free(sb);
1544 } else if (tok == T_CON) {
1545 val_t *val = *(val_t **)sp;
1546 free(val);
1547 } else if (tok == T_STRING) {
1548 buffer *str = *(buffer **)sp;
1549 free(str->data);
1550 free(str);
1551 }
1552 }
1553