lex.c revision 1.222 1 /* $NetBSD: lex.c,v 1.222 2024/03/03 16:09:01 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.222 2024/03/03 16:09:01 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 /*
730 * Analyze the lexical representation of the next character in the string
731 * literal list. At the end, only update the position information.
732 */
733 bool
734 quoted_next(const buffer *lit, quoted_iterator *it)
735 {
736 const char *s = lit->data;
737
738 *it = (quoted_iterator){ .start = it->end };
739
740 char delim = s[s[0] == 'L' ? 1 : 0];
741
742 bool in_the_middle = it->start > 0;
743 if (!in_the_middle) {
744 it->start = s[0] == 'L' ? 2 : 1;
745 it->end = it->start;
746 }
747
748 while (s[it->start] == delim) {
749 if (it->start + 1 == lit->len) {
750 it->end = it->start;
751 return false;
752 }
753 it->next_literal = in_the_middle;
754 it->start += 2;
755 }
756 it->end = it->start;
757
758 again:
759 switch (s[it->end]) {
760 case '\\':
761 it->end++;
762 goto backslash;
763 case '\n':
764 it->unescaped_newline = true;
765 return false;
766 default:
767 it->value = (unsigned char)s[it->end++];
768 return true;
769 }
770
771 backslash:
772 it->escaped = true;
773 if ('0' <= s[it->end] && s[it->end] <= '7')
774 goto octal_escape;
775 switch (s[it->end++]) {
776 case '\n':
777 goto again;
778 case 'a':
779 it->named_escape = true;
780 it->value = '\a';
781 it->invalid_escape = !allow_c90;
782 return true;
783 case 'b':
784 it->named_escape = true;
785 it->value = '\b';
786 return true;
787 case 'e':
788 it->named_escape = true;
789 it->value = '\033';
790 it->invalid_escape = !allow_gcc;
791 return true;
792 case 'f':
793 it->named_escape = true;
794 it->value = '\f';
795 return true;
796 case 'n':
797 it->named_escape = true;
798 it->value = '\n';
799 return true;
800 case 'r':
801 it->named_escape = true;
802 it->value = '\r';
803 return true;
804 case 't':
805 it->named_escape = true;
806 it->value = '\t';
807 return true;
808 case 'v':
809 it->named_escape = true;
810 it->value = '\v';
811 it->invalid_escape = !allow_c90;
812 return true;
813 case 'x':
814 goto hex_escape;
815 case '"':
816 it->literal_escape = true;
817 it->value = '"';
818 it->invalid_escape = !allow_c90 && delim == '\'';
819 return true;
820 case '?':
821 it->literal_escape = true;
822 it->value = '?';
823 it->invalid_escape = !allow_c90;
824 return true;
825 default:
826 it->invalid_escape = true;
827 /* FALLTHROUGH */
828 case '\'':
829 case '\\':
830 it->literal_escape = true;
831 it->value = (unsigned char)s[it->end - 1];
832 return true;
833 }
834
835 octal_escape:
836 it->octal_digits++;
837 it->value = s[it->end++] - '0';
838 if ('0' <= s[it->end] && s[it->end] <= '7') {
839 it->octal_digits++;
840 it->value = 8 * it->value + (s[it->end++] - '0');
841 if ('0' <= s[it->end] && s[it->end] <= '7') {
842 it->octal_digits++;
843 it->value = 8 * it->value + (s[it->end++] - '0');
844 it->overflow = it->value > TARG_UCHAR_MAX
845 && s[0] != 'L';
846 }
847 }
848 return true;
849
850 hex_escape:
851 for (;;) {
852 char ch = s[it->end];
853 unsigned digit_value;
854 if ('0' <= ch && ch <= '9')
855 digit_value = ch - '0';
856 else if ('A' <= ch && ch <= 'F')
857 digit_value = 10 + (ch - 'A');
858 else if ('a' <= ch && ch <= 'f')
859 digit_value = 10 + (ch - 'a');
860 else
861 break;
862
863 it->end++;
864 it->value = 16 * it->value + digit_value;
865 uint64_t limit = s[0] == 'L' ? TARG_UINT_MAX : TARG_UCHAR_MAX;
866 if (it->value > limit)
867 it->overflow = true;
868 if (it->hex_digits < 3)
869 it->hex_digits++;
870 }
871 it->missing_hex_digits = it->hex_digits == 0;
872 return true;
873 }
874
875 static void
876 check_quoted(const buffer *buf, bool complete, char delim)
877 {
878 quoted_iterator it = { .end = 0 }, prev = it;
879 for (; quoted_next(buf, &it); prev = it) {
880 if (it.missing_hex_digits)
881 /* no hex digits follow \x */
882 error(74);
883 if (it.hex_digits > 0 && !allow_c90)
884 /* \x undefined in traditional C */
885 warning(82);
886 else if (!it.invalid_escape)
887 ;
888 else if (it.value == '8' || it.value == '9')
889 /* bad octal digit '%c' */
890 warning(77, (int)it.value);
891 else if (it.literal_escape && it.value == '?')
892 /* \? undefined in traditional C */
893 warning(263);
894 else if (it.literal_escape && it.value == '"')
895 /* \" inside character constants undefined in ... */
896 warning(262);
897 else if (it.named_escape && it.value == '\a')
898 /* \a undefined in traditional C */
899 warning(81);
900 else if (it.named_escape && it.value == '\v')
901 /* \v undefined in traditional C */
902 warning(264);
903 else {
904 unsigned char ch = buf->data[it.end - 1];
905 if (isprint(ch))
906 /* dubious escape \%c */
907 warning(79, ch);
908 else
909 /* dubious escape \%o */
910 warning(80, ch);
911 }
912 if (it.overflow && it.hex_digits > 0)
913 /* overflow in hex escape */
914 warning(75);
915 if (it.overflow && it.octal_digits > 0)
916 /* character escape does not fit in character */
917 warning(76);
918 if (it.value < ' ' && !it.escaped && complete)
919 /* invisible character U+%04X in %s */
920 query_message(17, (unsigned)it.value, delim == '"'
921 ? "string literal" : "character constant");
922 if (prev.octal_digits > 0 && prev.octal_digits < 3
923 && !it.escaped && it.value >= '8' && it.value <= '9')
924 /* short octal escape '%.*s' followed by digit '%c' */
925 warning(356, (int)(prev.end - prev.start),
926 buf->data + prev.start, buf->data[it.start]);
927 }
928 if (it.unescaped_newline)
929 /* newline in string or char constant */
930 error(254);
931 if (!complete && delim == '"')
932 /* unterminated string constant */
933 error(258);
934 if (!complete && delim == '\'')
935 /* unterminated character constant */
936 error(253);
937 }
938
939 static buffer *
940 lex_quoted(char delim, bool wide)
941 {
942 bool complete;
943 buffer *buf = read_quoted(&complete, delim, wide);
944 check_quoted(buf, complete, delim);
945 return buf;
946 }
947
948 /* Called if lex found a leading "'". */
949 int
950 lex_character_constant(void)
951 {
952 buffer *buf = lex_quoted('\'', false);
953
954 size_t n = 0;
955 uint64_t val = 0;
956 quoted_iterator it = { .end = 0 };
957 while (quoted_next(buf, &it)) {
958 val = (val << CHAR_SIZE) + it.value;
959 n++;
960 }
961 if (n > sizeof(int) || (n > 1 && (pflag || hflag))) {
962 /*
963 * XXX: ^^ should rather be sizeof(TARG_INT). Luckily,
964 * sizeof(int) is the same on all supported platforms.
965 */
966 /* too many characters in character constant */
967 error(71);
968 } else if (n > 1)
969 /* multi-character character constant */
970 warning(294);
971 else if (n == 0 && !it.unescaped_newline)
972 /* empty character constant */
973 error(73);
974
975 int64_t cval = n == 1
976 ? convert_integer((int64_t)val, CHAR, CHAR_SIZE)
977 : (int64_t)val;
978
979 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
980 yylval.y_val->v_tspec = INT;
981 yylval.y_val->v_char_constant = true;
982 yylval.y_val->u.integer = cval;
983
984 return T_CON;
985 }
986
987 /*
988 * Called if lex found a leading L\'
989 */
990 int
991 lex_wide_character_constant(void)
992 {
993 buffer *buf = lex_quoted('\'', true);
994
995 static char wbuf[MB_LEN_MAX + 1];
996 size_t n = 0, nmax = MB_CUR_MAX;
997
998 quoted_iterator it = { .end = 0 };
999 while (quoted_next(buf, &it)) {
1000 if (n < nmax)
1001 wbuf[n] = (char)it.value;
1002 n++;
1003 }
1004
1005 wchar_t wc = 0;
1006 if (n == 0)
1007 /* empty character constant */
1008 error(73);
1009 else if (n > nmax) {
1010 n = nmax;
1011 /* too many characters in character constant */
1012 error(71);
1013 } else {
1014 wbuf[n] = '\0';
1015 (void)mbtowc(NULL, NULL, 0);
1016 if (mbtowc(&wc, wbuf, nmax) < 0)
1017 /* invalid multibyte character */
1018 error(291);
1019 }
1020
1021 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
1022 yylval.y_val->v_tspec = WCHAR_TSPEC;
1023 yylval.y_val->v_char_constant = true;
1024 yylval.y_val->u.integer = wc;
1025
1026 return T_CON;
1027 }
1028
1029 /* See https://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html */
1030 static void
1031 parse_line_directive_flags(const char *p,
1032 bool *is_begin, bool *is_end, bool *is_system)
1033 {
1034
1035 *is_begin = false;
1036 *is_end = false;
1037 *is_system = false;
1038
1039 while (*p != '\0') {
1040 while (isspace((unsigned char)*p))
1041 p++;
1042
1043 const char *word = p;
1044 while (*p != '\0' && !isspace((unsigned char)*p))
1045 p++;
1046 size_t len = (size_t)(p - word);
1047
1048 if (len == 1 && word[0] == '1')
1049 *is_begin = true;
1050 if (len == 1 && word[0] == '2')
1051 *is_end = true;
1052 if (len == 1 && word[0] == '3')
1053 *is_system = true;
1054 /* Flag '4' is only interesting for C++. */
1055 }
1056 }
1057
1058 /*
1059 * The first directive of the preprocessed translation unit provides the name
1060 * of the C source file as specified at the command line.
1061 */
1062 static void
1063 set_csrc_pos(void)
1064 {
1065 static bool done;
1066
1067 if (done)
1068 return;
1069 done = true;
1070 csrc_pos.p_file = curr_pos.p_file;
1071 outsrc(transform_filename(curr_pos.p_file, strlen(curr_pos.p_file)));
1072 }
1073
1074 /*
1075 * Called for preprocessor directives. Currently implemented are:
1076 * # pragma [argument...]
1077 * # lineno
1078 * # lineno "filename" [GCC-flag...]
1079 */
1080 void
1081 lex_directive(const char *yytext)
1082 {
1083 const char *p = yytext + 1; /* skip '#' */
1084
1085 while (*p == ' ' || *p == '\t')
1086 p++;
1087
1088 if (!isdigit((unsigned char)*p)) {
1089 if (strncmp(p, "pragma", 6) == 0
1090 && isspace((unsigned char)p[6]))
1091 return;
1092 goto error;
1093 }
1094
1095 char *end;
1096 long ln = strtol(--p, &end, 10);
1097 if (end == p)
1098 goto error;
1099 p = end;
1100
1101 if (*p != ' ' && *p != '\t' && *p != '\0')
1102 goto error;
1103 while (*p == ' ' || *p == '\t')
1104 p++;
1105
1106 if (*p != '\0') {
1107 if (*p != '"')
1108 goto error;
1109 const char *fn = ++p;
1110 while (*p != '"' && *p != '\0')
1111 p++;
1112 if (*p != '"')
1113 goto error;
1114 size_t fn_len = p++ - fn;
1115 if (fn_len > PATH_MAX)
1116 goto error;
1117 if (fn_len == 0) {
1118 fn = "{standard input}";
1119 fn_len = strlen(fn);
1120 }
1121 curr_pos.p_file = record_filename(fn, fn_len);
1122 set_csrc_pos();
1123
1124 bool is_begin, is_end, is_system;
1125 parse_line_directive_flags(p, &is_begin, &is_end, &is_system);
1126 update_location(curr_pos.p_file, (int)ln, is_begin, is_end);
1127 in_system_header = is_system;
1128 }
1129 curr_pos.p_line = (int)ln - 1;
1130 curr_pos.p_uniq = 0;
1131 if (curr_pos.p_file == csrc_pos.p_file) {
1132 csrc_pos.p_line = (int)ln - 1;
1133 csrc_pos.p_uniq = 0;
1134 }
1135 return;
1136
1137 error:
1138 /* undefined or invalid '#' directive */
1139 warning(255);
1140 }
1141
1142 /* Handle lint comments such as ARGSUSED. */
1143 void
1144 lex_comment(void)
1145 {
1146 int c;
1147 static const struct {
1148 const char name[18];
1149 bool arg;
1150 lint_comment comment;
1151 } keywtab[] = {
1152 { "ARGSUSED", true, LC_ARGSUSED },
1153 { "BITFIELDTYPE", false, LC_BITFIELDTYPE },
1154 { "CONSTCOND", false, LC_CONSTCOND },
1155 { "CONSTANTCOND", false, LC_CONSTCOND },
1156 { "CONSTANTCONDITION", false, LC_CONSTCOND },
1157 { "FALLTHRU", false, LC_FALLTHROUGH },
1158 { "FALLTHROUGH", false, LC_FALLTHROUGH },
1159 { "FALL THROUGH", false, LC_FALLTHROUGH },
1160 { "fallthrough", false, LC_FALLTHROUGH },
1161 { "LINTLIBRARY", false, LC_LINTLIBRARY },
1162 { "LINTED", true, LC_LINTED },
1163 { "LONGLONG", false, LC_LONGLONG },
1164 { "NOSTRICT", true, LC_LINTED },
1165 { "NOTREACHED", false, LC_NOTREACHED },
1166 { "PRINTFLIKE", true, LC_PRINTFLIKE },
1167 { "PROTOLIB", true, LC_PROTOLIB },
1168 { "SCANFLIKE", true, LC_SCANFLIKE },
1169 { "VARARGS", true, LC_VARARGS },
1170 };
1171 char keywd[32];
1172 char arg[32];
1173 size_t l, i;
1174 int a;
1175
1176 bool seen_end_of_comment = false;
1177
1178 while (c = read_byte(), isspace(c))
1179 continue;
1180
1181 /* Read the potential keyword to keywd */
1182 l = 0;
1183 while (c != EOF && l < sizeof(keywd) - 1 &&
1184 (isalpha(c) || isspace(c))) {
1185 if (islower(c) && l > 0 && isupper((unsigned char)keywd[0]))
1186 break;
1187 keywd[l++] = (char)c;
1188 c = read_byte();
1189 }
1190 while (l > 0 && isspace((unsigned char)keywd[l - 1]))
1191 l--;
1192 keywd[l] = '\0';
1193
1194 /* look for the keyword */
1195 for (i = 0; i < sizeof(keywtab) / sizeof(keywtab[0]); i++)
1196 if (strcmp(keywtab[i].name, keywd) == 0)
1197 goto found_keyword;
1198 goto skip_rest;
1199
1200 found_keyword:
1201 while (isspace(c))
1202 c = read_byte();
1203
1204 /* read the argument, if the keyword accepts one and there is one */
1205 l = 0;
1206 if (keywtab[i].arg) {
1207 while (isdigit(c) && l < sizeof(arg) - 1) {
1208 arg[l++] = (char)c;
1209 c = read_byte();
1210 }
1211 }
1212 arg[l] = '\0';
1213 a = l != 0 ? atoi(arg) : -1;
1214
1215 while (isspace(c))
1216 c = read_byte();
1217
1218 seen_end_of_comment = c == '*' && (c = read_byte()) == '/';
1219 if (!seen_end_of_comment && keywtab[i].comment != LC_LINTED)
1220 /* extra characters in lint comment */
1221 warning(257);
1222
1223 handle_lint_comment(keywtab[i].comment, a);
1224
1225 skip_rest:
1226 while (!seen_end_of_comment) {
1227 int lc = c;
1228 if ((c = read_byte()) == EOF) {
1229 /* unterminated comment */
1230 error(256);
1231 break;
1232 }
1233 if (lc == '*' && c == '/')
1234 seen_end_of_comment = true;
1235 }
1236 }
1237
1238 void
1239 lex_slash_slash_comment(void)
1240 {
1241 int c;
1242
1243 if (!allow_c99 && !allow_gcc)
1244 /* %s does not support '//' comments */
1245 gnuism(312, allow_c90 ? "C90" : "traditional C");
1246
1247 while ((c = read_byte()) != EOF && c != '\n')
1248 continue;
1249 }
1250
1251 /*
1252 * Clear flags for lint comments LINTED, LONGLONG and CONSTCOND.
1253 * clear_warn_flags is called after function definitions and global and
1254 * local declarations and definitions. It is also called between
1255 * the controlling expression and the body of control statements
1256 * (if, switch, for, while).
1257 */
1258 void
1259 clear_warn_flags(void)
1260 {
1261
1262 lwarn = LWARN_ALL;
1263 suppress_longlong = false;
1264 suppress_constcond = false;
1265 }
1266
1267 int
1268 lex_string(void)
1269 {
1270 yylval.y_string = lex_quoted('"', false);
1271 return T_STRING;
1272 }
1273
1274 static size_t
1275 wide_length(const buffer *buf)
1276 {
1277
1278 (void)mblen(NULL, 0);
1279 size_t len = 0, i = 0;
1280 while (i < buf->len) {
1281 int n = mblen(buf->data + i, MB_CUR_MAX);
1282 if (n == -1) {
1283 /* invalid multibyte character */
1284 error(291);
1285 break;
1286 }
1287 i += n > 1 ? n : 1;
1288 len++;
1289 }
1290 return len;
1291 }
1292
1293 int
1294 lex_wide_string(void)
1295 {
1296 buffer *buf = lex_quoted('"', true);
1297
1298 buffer str;
1299 buf_init(&str);
1300 quoted_iterator it = { .end = 0 };
1301 while (quoted_next(buf, &it))
1302 buf_add_char(&str, (char)it.value);
1303
1304 free(buf->data);
1305 *buf = (buffer) { .len = wide_length(&str) };
1306
1307 yylval.y_string = buf;
1308 return T_STRING;
1309 }
1310
1311 void
1312 lex_next_line(void)
1313 {
1314 curr_pos.p_line++;
1315 curr_pos.p_uniq = 0;
1316 debug_skip_indent();
1317 debug_printf("parsing %s:%d\n", curr_pos.p_file, curr_pos.p_line);
1318 if (curr_pos.p_file == csrc_pos.p_file) {
1319 csrc_pos.p_line++;
1320 csrc_pos.p_uniq = 0;
1321 }
1322 }
1323
1324 void
1325 lex_unknown_character(int c)
1326 {
1327
1328 /* unknown character \%o */
1329 error(250, c);
1330 }
1331
1332 /*
1333 * The scanner does not create new symbol table entries for symbols it cannot
1334 * find in the symbol table. This is to avoid putting undeclared symbols into
1335 * the symbol table if a syntax error occurs.
1336 *
1337 * getsym is called as soon as it is probably ok to put the symbol in the
1338 * symbol table. It is still possible that symbols are put in the symbol
1339 * table that are not completely declared due to syntax errors. To avoid too
1340 * many problems in this case, symbols get type 'int' in getsym.
1341 *
1342 * XXX calls to getsym should be delayed until declare_1_* is called.
1343 */
1344 sym_t *
1345 getsym(sbuf_t *sb)
1346 {
1347
1348 sym_t *sym = sb->sb_sym;
1349
1350 /*
1351 * During member declaration it is possible that name() looked for
1352 * symbols of type SK_VCFT, although it should have looked for symbols
1353 * of type SK_TAG. Same can happen for labels. Both cases are
1354 * compensated here.
1355 */
1356 if (sym_kind == SK_MEMBER || sym_kind == SK_LABEL) {
1357 if (sym == NULL || sym->s_kind == SK_VCFT)
1358 sym = symtab_search(sb->sb_name);
1359 }
1360
1361 if (sym != NULL) {
1362 lint_assert(sym->s_kind == sym_kind);
1363 set_sym_kind(SK_VCFT);
1364 free(sb);
1365 return sym;
1366 }
1367
1368 /* create a new symbol table entry */
1369
1370 /* labels must always be allocated at level 1 (outermost block) */
1371 decl_level *dl;
1372 if (sym_kind == SK_LABEL) {
1373 sym = level_zero_alloc(1, sizeof(*sym), "sym");
1374 char *s = level_zero_alloc(1, sb->sb_len + 1, "string");
1375 (void)memcpy(s, sb->sb_name, sb->sb_len + 1);
1376 sym->s_name = s;
1377 sym->s_block_level = 1;
1378 dl = dcs;
1379 while (dl->d_enclosing != NULL &&
1380 dl->d_enclosing->d_enclosing != NULL)
1381 dl = dl->d_enclosing;
1382 lint_assert(dl->d_kind == DLK_AUTO);
1383 } else {
1384 sym = block_zero_alloc(sizeof(*sym), "sym");
1385 sym->s_name = sb->sb_name;
1386 sym->s_block_level = block_level;
1387 dl = dcs;
1388 }
1389
1390 sym->s_def_pos = unique_curr_pos();
1391 if ((sym->s_kind = sym_kind) != SK_LABEL)
1392 sym->s_type = gettyp(INT);
1393
1394 set_sym_kind(SK_VCFT);
1395
1396 if (!in_gcc_attribute) {
1397 debug_printf("%s: symtab_add ", __func__);
1398 debug_sym("", sym, "\n");
1399 symtab_add(sym);
1400
1401 *dl->d_last_dlsym = sym;
1402 dl->d_last_dlsym = &sym->s_level_next;
1403 }
1404
1405 free(sb);
1406 return sym;
1407 }
1408
1409 /*
1410 * Construct a temporary symbol. The symbol name starts with a digit to avoid
1411 * name clashes with other identifiers.
1412 */
1413 sym_t *
1414 mktempsym(type_t *tp)
1415 {
1416 static unsigned n = 0;
1417 char *s = level_zero_alloc((size_t)block_level, 64, "string");
1418 sym_t *sym = block_zero_alloc(sizeof(*sym), "sym");
1419 scl_t scl;
1420
1421 (void)snprintf(s, 64, "%.8u_tmp", n++);
1422
1423 scl = dcs->d_scl;
1424 if (scl == NO_SCL)
1425 scl = block_level > 0 ? AUTO : EXTERN;
1426
1427 sym->s_name = s;
1428 sym->s_type = tp;
1429 sym->s_block_level = block_level;
1430 sym->s_scl = scl;
1431 sym->s_kind = SK_VCFT;
1432 sym->s_used = true;
1433 sym->s_set = true;
1434
1435 symtab_add(sym);
1436
1437 *dcs->d_last_dlsym = sym;
1438 dcs->d_last_dlsym = &sym->s_level_next;
1439
1440 return sym;
1441 }
1442
1443 /* Remove a symbol forever from the symbol table. */
1444 void
1445 rmsym(sym_t *sym)
1446 {
1447
1448 debug_step("rmsym '%s' %s '%s'",
1449 sym->s_name, symbol_kind_name(sym->s_kind),
1450 type_name(sym->s_type));
1451 symtab_remove(sym);
1452
1453 /* avoid that the symbol will later be put back to the symbol table */
1454 sym->s_block_level = -1;
1455 }
1456
1457 /*
1458 * Remove all symbols from the symbol table that have the same level as the
1459 * given symbol.
1460 */
1461 void
1462 symtab_remove_level(sym_t *syms)
1463 {
1464
1465 if (syms != NULL)
1466 debug_step("%s %d", __func__, syms->s_block_level);
1467
1468 /* Note the use of s_level_next instead of s_symtab_next. */
1469 for (sym_t *sym = syms; sym != NULL; sym = sym->s_level_next) {
1470 if (sym->s_block_level != -1) {
1471 debug_step("%s '%s' %s '%s' %d", __func__,
1472 sym->s_name, symbol_kind_name(sym->s_kind),
1473 type_name(sym->s_type), sym->s_block_level);
1474 symtab_remove(sym);
1475 sym->s_symtab_ref = NULL;
1476 }
1477 }
1478 }
1479
1480 /* Put a symbol into the symbol table. */
1481 void
1482 inssym(int level, sym_t *sym)
1483 {
1484
1485 debug_step("%s '%s' %s '%s' %d", __func__,
1486 sym->s_name, symbol_kind_name(sym->s_kind),
1487 type_name(sym->s_type), level);
1488 sym->s_block_level = level;
1489 symtab_add(sym);
1490
1491 /*
1492 * Placing the inner symbols to the beginning of the list ensures that
1493 * these symbols are preferred over symbols from the outer blocks that
1494 * happen to have the same name.
1495 */
1496 const sym_t *next = sym->s_symtab_next;
1497 if (next != NULL)
1498 lint_assert(sym->s_block_level >= next->s_block_level);
1499 }
1500
1501 /* Called at level 0 after syntax errors. */
1502 void
1503 clean_up_after_error(void)
1504 {
1505
1506 symtab_remove_locals();
1507
1508 while (mem_block_level > 0)
1509 level_free_all(mem_block_level--);
1510 }
1511
1512 /* Create a new symbol with the same name as an existing symbol. */
1513 sym_t *
1514 pushdown(const sym_t *sym)
1515 {
1516 sym_t *nsym;
1517
1518 debug_step("pushdown '%s' %s '%s'",
1519 sym->s_name, symbol_kind_name(sym->s_kind),
1520 type_name(sym->s_type));
1521 nsym = block_zero_alloc(sizeof(*nsym), "sym");
1522 lint_assert(sym->s_block_level <= block_level);
1523 nsym->s_name = sym->s_name;
1524 nsym->s_def_pos = unique_curr_pos();
1525 nsym->s_kind = sym->s_kind;
1526 nsym->s_block_level = block_level;
1527
1528 symtab_add(nsym);
1529
1530 *dcs->d_last_dlsym = nsym;
1531 dcs->d_last_dlsym = &nsym->s_level_next;
1532
1533 return nsym;
1534 }
1535
1536 /*
1537 * Free any dynamically allocated memory referenced by
1538 * the value stack or yylval.
1539 * The type of information in yylval is described by tok.
1540 */
1541 void
1542 freeyyv(void *sp, int tok)
1543 {
1544 if (tok == T_NAME || tok == T_TYPENAME) {
1545 sbuf_t *sb = *(sbuf_t **)sp;
1546 free(sb);
1547 } else if (tok == T_CON) {
1548 val_t *val = *(val_t **)sp;
1549 free(val);
1550 } else if (tok == T_STRING) {
1551 buffer *str = *(buffer **)sp;
1552 free(str->data);
1553 free(str);
1554 }
1555 }
1556