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