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