lex.c revision 1.121 1 /* $NetBSD: lex.c,v 1.121 2022/04/16 19:18:17 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) && !defined(lint)
41 __RCSID("$NetBSD: lex.c,v 1.121 2022/04/16 19:18:17 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 #define kwdef(name, token, scl, tspec, tqual, c90, c99, gcc, attr, deco) \
71 { \
72 name, token, scl, tspec, tqual, \
73 (c90) > 0, (c99) > 0, (gcc) > 0, (attr) > 0, \
74 ((deco) & 1) != 0, ((deco) & 2) != 0, ((deco) & 4) != 0, \
75 }
76 #define kwdef_token(name, token, c90, c99, gcc, deco) \
77 kwdef(name, token, 0, 0, 0, c90, c99, gcc, 0, deco)
78 #define kwdef_sclass(name, sclass, c90, c99, gcc, deco) \
79 kwdef(name, T_SCLASS, sclass, 0, 0, c90, c99, gcc, 0, deco)
80 #define kwdef_type(name, tspec, c90, c99, gcc, deco) \
81 kwdef(name, T_TYPE, 0, tspec, 0, c90, c99, gcc, 0, deco)
82 #define kwdef_tqual(name, tqual, c90, c99, gcc, deco) \
83 kwdef(name, T_QUAL, 0, 0, tqual, c90, c99, gcc, 0, deco)
84 #define kwdef_keyword(name, token) \
85 kwdef(name, token, 0, 0, 0, 0, 0, 0, 0, 1)
86 #define kwdef_gcc_attr(name, token) \
87 kwdef(name, token, 0, 0, 0, 0, 0, 1, 1, 5)
88
89 /* During initialization, these keywords are written to the symbol table. */
90 static const struct keyword {
91 const char *kw_name; /* keyword */
92 int kw_token; /* token returned by yylex() */
93 scl_t kw_scl; /* storage class if kw_token T_SCLASS */
94 tspec_t kw_tspec; /* type spec. if kw_token
95 * T_TYPE or T_STRUCT_OR_UNION */
96 tqual_t kw_tqual; /* type qual. if kw_token T_QUAL */
97 bool kw_c90:1; /* C90 keyword */
98 bool kw_c99:1; /* C99 keyword */
99 bool kw_gcc:1; /* GCC keyword */
100 bool kw_attr:1; /* GCC attribute, keyword */
101 bool kw_plain:1; /* 'name' */
102 bool kw_leading:1; /* '__name' */
103 bool kw_both:1; /* '__name__' */
104 } keywords[] = {
105 kwdef_gcc_attr( "alias", T_AT_ALIAS),
106 kwdef_keyword( "_Alignas", T_ALIGNAS),
107 kwdef_keyword( "_Alignof", T_ALIGNOF),
108 kwdef_gcc_attr( "aligned", T_AT_ALIGNED),
109 kwdef_token( "__alignof__", T_ALIGNOF, 0,0,0,1),
110 kwdef_gcc_attr( "alloc_size", T_AT_ALLOC_SIZE),
111 kwdef_gcc_attr( "always_inline",T_AT_ALWAYS_INLINE),
112 kwdef_token( "asm", T_ASM, 0,0,1,7),
113 kwdef_token( "attribute", T_ATTRIBUTE, 0,0,1,6),
114 kwdef_sclass( "auto", AUTO, 0,0,0,1),
115 kwdef_type( "_Bool", BOOL, 0,1,0,1),
116 kwdef_gcc_attr( "bounded", T_AT_BOUNDED),
117 kwdef_keyword( "break", T_BREAK),
118 kwdef_gcc_attr( "buffer", T_AT_BUFFER),
119 kwdef_token( "__builtin_offsetof", T_BUILTIN_OFFSETOF, 0,0,1,1),
120 kwdef_keyword( "case", T_CASE),
121 kwdef_type( "char", CHAR, 0,0,0,1),
122 kwdef_gcc_attr( "cold", T_AT_COLD),
123 kwdef_gcc_attr( "common", T_AT_COMMON),
124 kwdef_type( "_Complex", COMPLEX, 0,1,0,1),
125 kwdef_tqual( "const", CONST, 1,0,0,7),
126 kwdef_gcc_attr( "constructor", T_AT_CONSTRUCTOR),
127 kwdef_keyword( "continue", T_CONTINUE),
128 kwdef_keyword( "default", T_DEFAULT),
129 kwdef_gcc_attr( "deprecated", T_AT_DEPRECATED),
130 kwdef_gcc_attr( "destructor", T_AT_DESTRUCTOR),
131 kwdef_gcc_attr( "disable_sanitizer_instrumentation",
132 T_AT_DISABLE_SANITIZER_INSTRUMENTATION),
133 kwdef_keyword( "do", T_DO),
134 kwdef_type( "double", DOUBLE, 0,0,0,1),
135 kwdef_keyword( "else", T_ELSE),
136 kwdef_keyword( "enum", T_ENUM),
137 kwdef_token( "__extension__",T_EXTENSION, 0,0,1,1),
138 kwdef_sclass( "extern", EXTERN, 0,0,0,1),
139 kwdef_gcc_attr( "fallthrough", T_AT_FALLTHROUGH),
140 kwdef_type( "float", FLOAT, 0,0,0,1),
141 kwdef_keyword( "for", T_FOR),
142 kwdef_gcc_attr( "format", T_AT_FORMAT),
143 kwdef_gcc_attr( "format_arg", T_AT_FORMAT_ARG),
144 kwdef_token( "_Generic", T_GENERIC, 0,1,0,1),
145 kwdef_gcc_attr( "gnu_inline", T_AT_GNU_INLINE),
146 kwdef_gcc_attr( "gnu_printf", T_AT_FORMAT_GNU_PRINTF),
147 kwdef_keyword( "goto", T_GOTO),
148 kwdef_gcc_attr( "hot", T_AT_HOT),
149 kwdef_keyword( "if", T_IF),
150 kwdef_token( "__imag__", T_IMAG, 0,0,1,1),
151 kwdef_sclass( "inline", INLINE, 0,1,0,7),
152 kwdef_type( "int", INT, 0,0,0,1),
153 #ifdef INT128_SIZE
154 kwdef_type( "__int128_t", INT128, 0,1,0,1),
155 #endif
156 kwdef_type( "long", LONG, 0,0,0,1),
157 kwdef_gcc_attr( "malloc", T_AT_MALLOC),
158 kwdef_gcc_attr( "may_alias", T_AT_MAY_ALIAS),
159 kwdef_gcc_attr( "minbytes", T_AT_MINBYTES),
160 kwdef_gcc_attr( "mode", T_AT_MODE),
161 kwdef_gcc_attr("no_instrument_function",
162 T_AT_NO_INSTRUMENT_FUNCTION),
163 kwdef_gcc_attr( "no_sanitize", T_AT_NO_SANITIZE),
164 kwdef_gcc_attr( "no_sanitize_thread", T_AT_NO_SANITIZE_THREAD),
165 kwdef_gcc_attr( "noinline", T_AT_NOINLINE),
166 kwdef_gcc_attr( "nonnull", T_AT_NONNULL),
167 kwdef_gcc_attr( "nonstring", T_AT_NONSTRING),
168 kwdef_token( "_Noreturn", T_NORETURN, 0,1,0,1),
169 kwdef_gcc_attr( "noreturn", T_AT_NORETURN),
170 kwdef_gcc_attr( "nothrow", T_AT_NOTHROW),
171 kwdef_gcc_attr( "optimize", T_AT_OPTIMIZE),
172 kwdef_gcc_attr( "optnone", T_AT_OPTNONE),
173 kwdef_gcc_attr( "packed", T_AT_PACKED),
174 kwdef_token( "__packed", T_PACKED, 0,0,0,1),
175 kwdef_gcc_attr( "pcs", T_AT_PCS),
176 kwdef_gcc_attr( "printf", T_AT_FORMAT_PRINTF),
177 kwdef_gcc_attr( "pure", T_AT_PURE),
178 kwdef_token( "__real__", T_REAL, 0,0,1,1),
179 kwdef_sclass( "register", REG, 0,0,0,1),
180 kwdef_gcc_attr( "regparm", T_AT_REGPARM),
181 kwdef_tqual( "restrict", RESTRICT, 0,1,0,7),
182 kwdef_keyword( "return", T_RETURN),
183 kwdef_gcc_attr( "returns_nonnull",T_AT_RETURNS_NONNULL),
184 kwdef_gcc_attr( "returns_twice",T_AT_RETURNS_TWICE),
185 kwdef_gcc_attr( "scanf", T_AT_FORMAT_SCANF),
186 kwdef( "section", T_AT_SECTION, 0,0,0,0,0,1,1,7),
187 kwdef_gcc_attr( "sentinel", T_AT_SENTINEL),
188 kwdef_type( "short", SHORT, 0,0,0,1),
189 kwdef_type( "signed", SIGNED, 1,0,0,3),
190 kwdef_keyword( "sizeof", T_SIZEOF),
191 kwdef_sclass( "static", STATIC, 0,0,0,1),
192 kwdef_keyword( "_Static_assert", T_STATIC_ASSERT),
193 kwdef_gcc_attr( "strfmon", T_AT_FORMAT_STRFMON),
194 kwdef_gcc_attr( "strftime", T_AT_FORMAT_STRFTIME),
195 kwdef_gcc_attr( "string", T_AT_STRING),
196 kwdef("struct", T_STRUCT_OR_UNION, 0, STRUCT, 0, 0,0,0,0,1),
197 kwdef_keyword( "switch", T_SWITCH),
198 kwdef_token( "__symbolrename", T_SYMBOLRENAME, 0,0,0,1),
199 kwdef_gcc_attr( "syslog", T_AT_FORMAT_SYSLOG),
200 kwdef_gcc_attr( "target", T_AT_TARGET),
201 kwdef_tqual( "__thread", THREAD, 0,0,1,1),
202 kwdef_tqual( "_Thread_local", THREAD, 0,1,0,1),
203 kwdef_gcc_attr( "tls_model", T_AT_TLS_MODEL),
204 kwdef_gcc_attr( "transparent_union", T_AT_TUNION),
205 kwdef_sclass( "typedef", TYPEDEF, 0,0,0,1),
206 kwdef_token( "typeof", T_TYPEOF, 0,0,1,7),
207 #ifdef INT128_SIZE
208 kwdef_type( "__uint128_t", UINT128, 0,1,0,1),
209 #endif
210 kwdef("union", T_STRUCT_OR_UNION, 0, UNION, 0, 0,0,0,0,1),
211 kwdef_type( "unsigned", UNSIGN, 0,0,0,1),
212 kwdef_gcc_attr( "unused", T_AT_UNUSED),
213 kwdef_gcc_attr( "used", T_AT_USED),
214 kwdef_gcc_attr( "visibility", T_AT_VISIBILITY),
215 kwdef_type( "void", VOID, 0,0,0,1),
216 kwdef_tqual( "volatile", VOLATILE, 1,0,0,7),
217 kwdef_gcc_attr( "warn_unused_result", T_AT_WARN_UNUSED_RESULT),
218 kwdef_gcc_attr( "weak", T_AT_WEAK),
219 kwdef_keyword( "while", T_WHILE),
220 kwdef(NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0),
221 #undef kwdef
222 #undef kwdef_token
223 #undef kwdef_sclass
224 #undef kwdef_type
225 #undef kwdef_tqual
226 #undef kwdef_keyword
227 #undef kwdef_gcc_attr
228 };
229
230 /* Symbol table */
231 static sym_t *symtab[HSHSIZ1];
232
233 /* type of next expected symbol */
234 symt_t symtyp;
235
236
237 static int get_escaped_char(int);
238
239
240 static unsigned int
241 hash(const char *s)
242 {
243 unsigned int v;
244 const char *p;
245
246 v = 0;
247 for (p = s; *p != '\0'; p++) {
248 v = (v << 4) + (unsigned char)*p;
249 v ^= v >> 28;
250 }
251 return v % HSHSIZ1;
252 }
253
254 static void
255 symtab_add(sym_t *sym)
256 {
257 unsigned int h;
258
259 h = hash(sym->s_name);
260 if ((sym->s_symtab_next = symtab[h]) != NULL)
261 symtab[h]->s_symtab_ref = &sym->s_symtab_next;
262 sym->s_symtab_ref = &symtab[h];
263 symtab[h] = sym;
264 }
265
266 static sym_t *
267 symtab_search(sbuf_t *sb)
268 {
269
270 unsigned int h = hash(sb->sb_name);
271 for (sym_t *sym = symtab[h]; sym != NULL; sym = sym->s_symtab_next) {
272 if (strcmp(sym->s_name, sb->sb_name) != 0)
273 continue;
274
275 const struct keyword *kw = sym->s_keyword;
276 if (kw != NULL && !kw->kw_attr)
277 return sym;
278 if (kw != NULL && in_gcc_attribute)
279 return sym;
280 if (kw == NULL && !in_gcc_attribute && sym->s_kind == symtyp)
281 return sym;
282 }
283
284 return NULL;
285 }
286
287 static void
288 symtab_remove(sym_t *sym)
289 {
290
291 if ((*sym->s_symtab_ref = sym->s_symtab_next) != NULL)
292 sym->s_symtab_next->s_symtab_ref = sym->s_symtab_ref;
293 sym->s_symtab_next = NULL;
294 }
295
296 static void
297 symtab_remove_locals(void)
298 {
299
300 for (size_t i = 0; i < HSHSIZ1; i++) {
301 for (sym_t *sym = symtab[i]; sym != NULL; ) {
302 sym_t *next = sym->s_symtab_next;
303 if (sym->s_block_level >= 1)
304 symtab_remove(sym);
305 sym = next;
306 }
307 }
308 }
309
310 #ifdef DEBUG
311 static int
312 sym_by_name(const void *va, const void *vb)
313 {
314 const sym_t *a = *(const sym_t *const *)va;
315 const sym_t *b = *(const sym_t *const *)vb;
316
317 return strcmp(a->s_name, b->s_name);
318 }
319
320 struct syms {
321 const sym_t **items;
322 size_t len;
323 size_t cap;
324 };
325
326 static void
327 syms_add(struct syms *syms, const sym_t *sym)
328 {
329 while (syms->len >= syms->cap) {
330 syms->cap *= 2;
331 syms->items = xrealloc(syms->items,
332 syms->cap * sizeof(syms->items[0]));
333 }
334 syms->items[syms->len++] = sym;
335 }
336
337 void
338 debug_symtab(void)
339 {
340 struct syms syms = { xcalloc(64, sizeof(syms.items[0])), 0, 64 };
341
342 for (int level = -1;; level++) {
343 bool more = false;
344 size_t n = sizeof(symtab) / sizeof(symtab[0]);
345
346 syms.len = 0;
347 for (size_t i = 0; i < n; i++) {
348 for (sym_t *sym = symtab[i]; sym != NULL;) {
349 if (sym->s_block_level == level &&
350 sym->s_keyword == NULL)
351 syms_add(&syms, sym);
352 if (sym->s_block_level > level)
353 more = true;
354 sym = sym->s_symtab_next;
355 }
356 }
357
358 if (syms.len > 0) {
359 debug_printf("symbol table level %d\n", level);
360 debug_indent_inc();
361 qsort(syms.items, syms.len, sizeof(syms.items[0]),
362 sym_by_name);
363 for (size_t i = 0; i < syms.len; i++)
364 debug_sym("", syms.items[i], "\n");
365 debug_indent_dec();
366
367 lint_assert(level != -1);
368 }
369
370 if (!more)
371 break;
372 }
373
374 free(syms.items);
375 }
376 #endif
377
378 static void
379 add_keyword(const struct keyword *kw, bool leading, bool trailing)
380 {
381 sym_t *sym;
382 char buf[256];
383 const char *name;
384
385 if (!leading && !trailing) {
386 name = kw->kw_name;
387 } else {
388 (void)snprintf(buf, sizeof(buf), "%s%s%s",
389 leading ? "__" : "", kw->kw_name, trailing ? "__" : "");
390 name = xstrdup(buf);
391 }
392
393 sym = block_zero_alloc(sizeof(*sym));
394 sym->s_name = name;
395 sym->s_keyword = kw;
396 sym->u.s_keyword.sk_token = kw->kw_token;
397 if (kw->kw_token == T_TYPE || kw->kw_token == T_STRUCT_OR_UNION) {
398 sym->u.s_keyword.sk_tspec = kw->kw_tspec;
399 } else if (kw->kw_token == T_SCLASS) {
400 sym->s_scl = kw->kw_scl;
401 } else if (kw->kw_token == T_QUAL) {
402 sym->u.s_keyword.sk_qualifier = kw->kw_tqual;
403 }
404
405 symtab_add(sym);
406 }
407
408 /*
409 * All keywords are written to the symbol table. This saves us looking
410 * in an extra table for each name we found.
411 */
412 void
413 initscan(void)
414 {
415 const struct keyword *kw;
416
417 for (kw = keywords; kw->kw_name != NULL; kw++) {
418 if ((kw->kw_c90 || kw->kw_c99) && tflag)
419 continue;
420 /* FIXME: C99 and GCC are independent. */
421 if (kw->kw_c99 && !(Sflag || allow_gcc))
422 continue;
423 if (kw->kw_gcc && !allow_gcc)
424 continue;
425 if (kw->kw_plain)
426 add_keyword(kw, false, false);
427 if (kw->kw_leading)
428 add_keyword(kw, true, false);
429 if (kw->kw_both)
430 add_keyword(kw, true, true);
431 }
432 }
433
434 /*
435 * Read a character and ensure that it is positive (except EOF).
436 * Increment line count(s) if necessary.
437 */
438 static int
439 inpc(void)
440 {
441 int c;
442
443 if ((c = lex_input()) == EOF)
444 return c;
445 c &= CHAR_MASK;
446 if (c == '\0')
447 return EOF; /* lex returns 0 on EOF. */
448 if (c == '\n')
449 lex_next_line();
450 return c;
451 }
452
453 static int
454 lex_keyword(sym_t *sym)
455 {
456 int t;
457
458 if ((t = sym->u.s_keyword.sk_token) == T_SCLASS) {
459 yylval.y_scl = sym->s_scl;
460 } else if (t == T_TYPE || t == T_STRUCT_OR_UNION) {
461 yylval.y_tspec = sym->u.s_keyword.sk_tspec;
462 } else if (t == T_QUAL) {
463 yylval.y_tqual = sym->u.s_keyword.sk_qualifier;
464 }
465 return t;
466 }
467
468 /*
469 * Lex has found a letter followed by zero or more letters or digits.
470 * It looks for a symbol in the symbol table with the same name. This
471 * symbol must either be a keyword or a symbol of the type required by
472 * symtyp (label, member, tag, ...).
473 *
474 * If it is a keyword, the token is returned. In some cases it is described
475 * more deeply by data written to yylval.
476 *
477 * If it is a symbol, T_NAME is returned and the name is stored in yylval.
478 * If there is already a symbol of the same name and type in the symbol
479 * table, yylval.y_name->sb_sym points there.
480 */
481 extern int
482 lex_name(const char *yytext, size_t yyleng)
483 {
484 char *s;
485 sbuf_t *sb;
486 sym_t *sym;
487 int tok;
488
489 sb = xmalloc(sizeof(*sb));
490 sb->sb_name = yytext;
491 sb->sb_len = yyleng;
492 if ((sym = symtab_search(sb)) != NULL && sym->s_keyword != NULL) {
493 free(sb);
494 return lex_keyword(sym);
495 }
496
497 sb->sb_sym = sym;
498
499 if (sym != NULL) {
500 lint_assert(block_level >= sym->s_block_level);
501 sb->sb_name = sym->s_name;
502 tok = sym->s_scl == TYPEDEF ? T_TYPENAME : T_NAME;
503 } else {
504 s = block_zero_alloc(yyleng + 1);
505 (void)memcpy(s, yytext, yyleng + 1);
506 sb->sb_name = s;
507 tok = T_NAME;
508 }
509
510 yylval.y_name = sb;
511 return tok;
512 }
513
514 /*
515 * Convert a string representing an integer into internal representation.
516 * Return T_CON, storing the numeric value in yylval, for yylex.
517 */
518 int
519 lex_integer_constant(const char *yytext, size_t yyleng, int base)
520 {
521 int l_suffix, u_suffix;
522 size_t len;
523 const char *cp;
524 char c, *eptr;
525 tspec_t typ;
526 bool ansiu;
527 bool warned = false;
528 uint64_t uq = 0;
529
530 /* C11 6.4.4.1p5 */
531 static const tspec_t suffix_type[2][3] = {
532 { INT, LONG, QUAD, },
533 { UINT, ULONG, UQUAD, }
534 };
535
536 cp = yytext;
537 len = yyleng;
538
539 /* skip 0[xX] or 0[bB] */
540 if (base == 16 || base == 2) {
541 cp += 2;
542 len -= 2;
543 }
544
545 /* read suffixes */
546 l_suffix = u_suffix = 0;
547 for (;;) {
548 if ((c = cp[len - 1]) == 'l' || c == 'L') {
549 l_suffix++;
550 } else if (c == 'u' || c == 'U') {
551 u_suffix++;
552 } else {
553 break;
554 }
555 len--;
556 }
557 if (l_suffix > 2 || u_suffix > 1) {
558 /* malformed integer constant */
559 warning(251);
560 if (l_suffix > 2)
561 l_suffix = 2;
562 if (u_suffix > 1)
563 u_suffix = 1;
564 }
565 if (tflag && u_suffix != 0) {
566 /* suffix U is illegal in traditional C */
567 warning(97);
568 }
569 typ = suffix_type[u_suffix][l_suffix];
570
571 errno = 0;
572
573 uq = (uint64_t)strtoull(cp, &eptr, base);
574 lint_assert(eptr == cp + len);
575 if (errno != 0) {
576 /* integer constant out of range */
577 warning(252);
578 warned = true;
579 }
580
581 /*
582 * If the value is too big for the current type, we must choose
583 * another type.
584 */
585 ansiu = false;
586 switch (typ) {
587 case INT:
588 if (uq <= TARG_INT_MAX) {
589 /* ok */
590 } else if (uq <= TARG_UINT_MAX && base != 10) {
591 typ = UINT;
592 } else if (uq <= TARG_LONG_MAX) {
593 typ = LONG;
594 } else {
595 typ = ULONG;
596 if (uq > TARG_ULONG_MAX && !warned) {
597 /* integer constant out of range */
598 warning(252);
599 }
600 }
601 if (typ == UINT || typ == ULONG) {
602 if (tflag) {
603 typ = LONG;
604 } else if (!sflag) {
605 /*
606 * Remember that the constant is unsigned
607 * only in ANSI C
608 */
609 ansiu = true;
610 }
611 }
612 break;
613 case UINT:
614 if (uq > TARG_UINT_MAX) {
615 typ = ULONG;
616 if (uq > TARG_ULONG_MAX && !warned) {
617 /* integer constant out of range */
618 warning(252);
619 }
620 }
621 break;
622 case LONG:
623 if (uq > TARG_LONG_MAX && !tflag) {
624 typ = ULONG;
625 if (!sflag)
626 ansiu = true;
627 if (uq > TARG_ULONG_MAX && !warned) {
628 /* integer constant out of range */
629 warning(252);
630 }
631 }
632 break;
633 case ULONG:
634 if (uq > TARG_ULONG_MAX && !warned) {
635 /* integer constant out of range */
636 warning(252);
637 }
638 break;
639 case QUAD:
640 if (uq > TARG_QUAD_MAX && !tflag) {
641 typ = UQUAD;
642 if (!sflag)
643 ansiu = true;
644 }
645 break;
646 case UQUAD:
647 if (uq > TARG_UQUAD_MAX && !warned) {
648 /* integer constant out of range */
649 warning(252);
650 }
651 break;
652 default:
653 break;
654 }
655
656 uq = (uint64_t)convert_integer((int64_t)uq, typ, 0);
657
658 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
659 yylval.y_val->v_tspec = typ;
660 yylval.y_val->v_unsigned_since_c90 = ansiu;
661 yylval.y_val->v_quad = (int64_t)uq;
662
663 return T_CON;
664 }
665
666 /*
667 * Extend or truncate q to match t. If t is signed, sign-extend.
668 *
669 * len is the number of significant bits. If len is -1, len is set
670 * to the width of type t.
671 */
672 int64_t
673 convert_integer(int64_t q, tspec_t t, unsigned int len)
674 {
675 uint64_t vbits;
676
677 if (len == 0)
678 len = size_in_bits(t);
679
680 vbits = value_bits(len);
681 return t == PTR || is_uinteger(t) || ((q & bit(len - 1)) == 0)
682 ? (int64_t)(q & vbits)
683 : (int64_t)(q | ~vbits);
684 }
685
686 /*
687 * Convert a string representing a floating point value into its numerical
688 * representation. Type and value are returned in yylval.
689 *
690 * XXX Currently it is not possible to convert constants of type
691 * long double which are greater than DBL_MAX.
692 */
693 int
694 lex_floating_constant(const char *yytext, size_t yyleng)
695 {
696 const char *cp;
697 size_t len;
698 tspec_t typ;
699 char c, *eptr;
700 double d;
701 float f = 0;
702
703 cp = yytext;
704 len = yyleng;
705
706 if (cp[len - 1] == 'i')
707 len--; /* imaginary, do nothing for now */
708
709 if ((c = cp[len - 1]) == 'f' || c == 'F') {
710 typ = FLOAT;
711 len--;
712 } else if (c == 'l' || c == 'L') {
713 typ = LDOUBLE;
714 len--;
715 } else {
716 if (c == 'd' || c == 'D')
717 len--;
718 typ = DOUBLE;
719 }
720
721 if (tflag && typ != DOUBLE) {
722 /* suffixes F and L are illegal in traditional C */
723 warning(98);
724 }
725
726 errno = 0;
727 d = strtod(cp, &eptr);
728 if (eptr != cp + len) {
729 switch (*eptr) {
730 /*
731 * XXX: non-native non-current strtod() may not handle hex
732 * floats, ignore the rest if we find traces of hex float
733 * syntax...
734 */
735 case 'p':
736 case 'P':
737 case 'x':
738 case 'X':
739 d = 0;
740 errno = 0;
741 break;
742 default:
743 INTERNAL_ERROR("lex_floating_constant(%s->%s)",
744 cp, eptr);
745 }
746 }
747 if (errno != 0)
748 /* floating-point constant out of range */
749 warning(248);
750
751 if (typ == FLOAT) {
752 f = (float)d;
753 if (isfinite(f) == 0) {
754 /* floating-point constant out of range */
755 warning(248);
756 f = f > 0 ? FLT_MAX : -FLT_MAX;
757 }
758 }
759
760 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
761 yylval.y_val->v_tspec = typ;
762 if (typ == FLOAT) {
763 yylval.y_val->v_ldbl = f;
764 } else {
765 yylval.y_val->v_ldbl = d;
766 }
767
768 return T_CON;
769 }
770
771 int
772 lex_operator(int t, op_t o)
773 {
774
775 yylval.y_op = o;
776 return t;
777 }
778
779 /* Called if lex found a leading "'". */
780 int
781 lex_character_constant(void)
782 {
783 size_t n;
784 int val, c;
785
786 n = 0;
787 val = 0;
788 while ((c = get_escaped_char('\'')) >= 0) {
789 val = (val << CHAR_SIZE) + c;
790 n++;
791 }
792 if (c == -2) {
793 /* unterminated character constant */
794 error(253);
795 } else if (n > sizeof(int) || (n > 1 && (pflag || hflag))) {
796 /* XXX: should rather be sizeof(TARG_INT) */
797
798 /* too many characters in character constant */
799 error(71);
800 } else if (n > 1) {
801 /* multi-character character constant */
802 warning(294);
803 } else if (n == 0) {
804 /* empty character constant */
805 error(73);
806 }
807 if (n == 1)
808 val = (int)convert_integer(val, CHAR, CHAR_SIZE);
809
810 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
811 yylval.y_val->v_tspec = INT;
812 yylval.y_val->v_quad = val;
813
814 return T_CON;
815 }
816
817 /*
818 * Called if lex found a leading L\'
819 */
820 int
821 lex_wide_character_constant(void)
822 {
823 static char buf[MB_LEN_MAX + 1];
824 size_t n, nmax;
825 int c;
826 wchar_t wc;
827
828 nmax = MB_CUR_MAX;
829
830 n = 0;
831 while ((c = get_escaped_char('\'')) >= 0) {
832 if (n < nmax)
833 buf[n] = (char)c;
834 n++;
835 }
836
837 wc = 0;
838
839 if (c == -2) {
840 /* unterminated character constant */
841 error(253);
842 } else if (n == 0) {
843 /* empty character constant */
844 error(73);
845 } else if (n > nmax) {
846 n = nmax;
847 /* too many characters in character constant */
848 error(71);
849 } else {
850 buf[n] = '\0';
851 (void)mbtowc(NULL, NULL, 0);
852 if (mbtowc(&wc, buf, nmax) < 0)
853 /* invalid multibyte character */
854 error(291);
855 }
856
857 yylval.y_val = xcalloc(1, sizeof(*yylval.y_val));
858 yylval.y_val->v_tspec = WCHAR;
859 yylval.y_val->v_quad = wc;
860
861 return T_CON;
862 }
863
864 /*
865 * Read a character which is part of a character constant or of a string
866 * and handle escapes.
867 *
868 * The argument is the character which delimits the character constant or
869 * string.
870 *
871 * Returns -1 if the end of the character constant or string is reached,
872 * -2 if the EOF is reached, and the character otherwise.
873 */
874 static int
875 get_escaped_char(int delim)
876 {
877 static int pbc = -1;
878 int n, c, v;
879
880 if (pbc == -1) {
881 c = inpc();
882 } else {
883 c = pbc;
884 pbc = -1;
885 }
886 if (c == delim)
887 return -1;
888 switch (c) {
889 case '\n':
890 if (tflag) {
891 /* newline in string or char constant */
892 error(254);
893 return -2;
894 }
895 return c;
896 case 0:
897 /* syntax error '%s' */
898 error(249, "EOF or null byte in literal");
899 return -2;
900 case EOF:
901 return -2;
902 case '\\':
903 switch (c = inpc()) {
904 case '"':
905 if (tflag && delim == '\'')
906 /* \" inside character constants undef... */
907 warning(262);
908 return '"';
909 case '\'':
910 return '\'';
911 case '?':
912 if (tflag)
913 /* \? undefined in traditional C */
914 warning(263);
915 return '?';
916 case '\\':
917 return '\\';
918 case 'a':
919 if (tflag)
920 /* \a undefined in traditional C */
921 warning(81);
922 return '\a';
923 case 'b':
924 return '\b';
925 case 'f':
926 return '\f';
927 case 'n':
928 return '\n';
929 case 'r':
930 return '\r';
931 case 't':
932 return '\t';
933 case 'v':
934 if (tflag)
935 /* \v undefined in traditional C */
936 warning(264);
937 return '\v';
938 case '8': case '9':
939 /* bad octal digit %c */
940 warning(77, c);
941 /* FALLTHROUGH */
942 case '0': case '1': case '2': case '3':
943 case '4': case '5': case '6': case '7':
944 n = 3;
945 v = 0;
946 do {
947 v = (v << 3) + (c - '0');
948 c = inpc();
949 } while (--n > 0 && '0' <= c && c <= '7');
950 pbc = c;
951 if (v > TARG_UCHAR_MAX) {
952 /* character escape does not fit in character */
953 warning(76);
954 v &= CHAR_MASK;
955 }
956 return v;
957 case 'x':
958 if (tflag)
959 /* \x undefined in traditional C */
960 warning(82);
961 v = 0;
962 n = 0;
963 while (c = inpc(), isxdigit(c)) {
964 c = isdigit(c) ?
965 c - '0' : toupper(c) - 'A' + 10;
966 v = (v << 4) + c;
967 if (n >= 0) {
968 if ((v & ~CHAR_MASK) != 0) {
969 /* overflow in hex escape */
970 warning(75);
971 n = -1;
972 } else {
973 n++;
974 }
975 }
976 }
977 pbc = c;
978 if (n == 0) {
979 /* no hex digits follow \x */
980 error(74);
981 } if (n == -1) {
982 v &= CHAR_MASK;
983 }
984 return v;
985 case '\n':
986 return get_escaped_char(delim);
987 case EOF:
988 return -2;
989 default:
990 if (isprint(c)) {
991 /* dubious escape \%c */
992 warning(79, c);
993 } else {
994 /* dubious escape \%o */
995 warning(80, c);
996 }
997 }
998 }
999 return c;
1000 }
1001
1002 /* See https://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html */
1003 static void
1004 parse_line_directive_flags(const char *p,
1005 bool *is_begin, bool *is_end, bool *is_system)
1006 {
1007
1008 *is_begin = false;
1009 *is_end = false;
1010 *is_system = false;
1011
1012 while (*p != '\0') {
1013 const char *word_start, *word_end;
1014
1015 while (ch_isspace(*p))
1016 p++;
1017
1018 word_start = p;
1019 while (*p != '\0' && !ch_isspace(*p))
1020 p++;
1021 word_end = p;
1022
1023 if (word_end - word_start == 1 && word_start[0] == '1')
1024 *is_begin = true;
1025 if (word_end - word_start == 1 && word_start[0] == '2')
1026 *is_end = true;
1027 if (word_end - word_start == 1 && word_start[0] == '3')
1028 *is_system = true;
1029 /* Flag '4' is only interesting for C++. */
1030 }
1031 }
1032
1033 /*
1034 * Called for preprocessor directives. Currently implemented are:
1035 * # pragma [argument...]
1036 * # lineno
1037 * # lineno "filename"
1038 * # lineno "filename" GCC-flag...
1039 */
1040 void
1041 lex_directive(const char *yytext)
1042 {
1043 const char *cp, *fn;
1044 char c, *eptr;
1045 size_t fnl;
1046 long ln;
1047 bool is_begin, is_end, is_system;
1048
1049 static bool first = true;
1050
1051 /* Go to first non-whitespace after # */
1052 for (cp = yytext + 1; (c = *cp) == ' ' || c == '\t'; cp++)
1053 continue;
1054
1055 if (!ch_isdigit(c)) {
1056 if (strncmp(cp, "pragma", 6) == 0 && ch_isspace(cp[6]))
1057 return;
1058 error:
1059 /* undefined or invalid # directive */
1060 warning(255);
1061 return;
1062 }
1063 ln = strtol(--cp, &eptr, 10);
1064 if (eptr == cp)
1065 goto error;
1066 if ((c = *(cp = eptr)) != ' ' && c != '\t' && c != '\0')
1067 goto error;
1068 while ((c = *cp++) == ' ' || c == '\t')
1069 continue;
1070 if (c != '\0') {
1071 if (c != '"')
1072 goto error;
1073 fn = cp;
1074 while ((c = *cp) != '"' && c != '\0')
1075 cp++;
1076 if (c != '"')
1077 goto error;
1078 if ((fnl = cp++ - fn) > PATH_MAX)
1079 goto error;
1080 /* empty string means stdin */
1081 if (fnl == 0) {
1082 fn = "{standard input}";
1083 fnl = 16; /* strlen (fn) */
1084 }
1085 curr_pos.p_file = record_filename(fn, fnl);
1086 /*
1087 * If this is the first directive, the name is the name
1088 * of the C source file as specified at the command line.
1089 * It is written to the output file.
1090 */
1091 if (first) {
1092 csrc_pos.p_file = curr_pos.p_file;
1093 outsrc(transform_filename(curr_pos.p_file,
1094 strlen(curr_pos.p_file)));
1095 first = false;
1096 }
1097
1098 parse_line_directive_flags(cp, &is_begin, &is_end, &is_system);
1099 update_location(curr_pos.p_file, (int)ln, is_begin, is_end);
1100 in_system_header = is_system;
1101 }
1102 curr_pos.p_line = (int)ln - 1;
1103 curr_pos.p_uniq = 0;
1104 if (curr_pos.p_file == csrc_pos.p_file) {
1105 csrc_pos.p_line = (int)ln - 1;
1106 csrc_pos.p_uniq = 0;
1107 }
1108 }
1109
1110 /*
1111 * Handle lint comments such as ARGSUSED.
1112 *
1113 * If one of these comments is recognized, the argument, if any, is
1114 * parsed and a function which handles this comment is called.
1115 */
1116 void
1117 lex_comment(void)
1118 {
1119 int c, lc;
1120 static const struct {
1121 const char *keywd;
1122 bool arg;
1123 void (*func)(int);
1124 } keywtab[] = {
1125 { "ARGSUSED", true, argsused },
1126 { "BITFIELDTYPE", false, bitfieldtype },
1127 { "CONSTCOND", false, constcond },
1128 { "CONSTANTCOND", false, constcond },
1129 { "CONSTANTCONDITION", false, constcond },
1130 { "FALLTHRU", false, fallthru },
1131 { "FALLTHROUGH", false, fallthru },
1132 { "FALL THROUGH", false, fallthru },
1133 { "fallthrough", false, fallthru },
1134 { "LINTLIBRARY", false, lintlib },
1135 { "LINTED", true, linted },
1136 { "LONGLONG", false, longlong },
1137 { "NOSTRICT", true, linted },
1138 { "NOTREACHED", false, not_reached },
1139 { "PRINTFLIKE", true, printflike },
1140 { "PROTOLIB", true, protolib },
1141 { "SCANFLIKE", true, scanflike },
1142 { "VARARGS", true, varargs },
1143 };
1144 char keywd[32];
1145 char arg[32];
1146 size_t l, i;
1147 int a;
1148 bool eoc;
1149
1150 eoc = false;
1151
1152 /* Skip whitespace after the start of the comment */
1153 while (c = inpc(), isspace(c))
1154 continue;
1155
1156 /* Read the potential keyword to keywd */
1157 l = 0;
1158 while (c != EOF && l < sizeof(keywd) - 1 &&
1159 (isalpha(c) || isspace(c))) {
1160 if (islower(c) && l > 0 && ch_isupper(keywd[0]))
1161 break;
1162 keywd[l++] = (char)c;
1163 c = inpc();
1164 }
1165 while (l > 0 && ch_isspace(keywd[l - 1]))
1166 l--;
1167 keywd[l] = '\0';
1168
1169 /* look for the keyword */
1170 for (i = 0; i < sizeof(keywtab) / sizeof(keywtab[0]); i++) {
1171 if (strcmp(keywtab[i].keywd, keywd) == 0)
1172 break;
1173 }
1174 if (i == sizeof(keywtab) / sizeof(keywtab[0]))
1175 goto skip_rest;
1176
1177 /* skip whitespace after the keyword */
1178 while (isspace(c))
1179 c = inpc();
1180
1181 /* read the argument, if the keyword accepts one and there is one */
1182 l = 0;
1183 if (keywtab[i].arg) {
1184 while (isdigit(c) && l < sizeof(arg) - 1) {
1185 arg[l++] = (char)c;
1186 c = inpc();
1187 }
1188 }
1189 arg[l] = '\0';
1190 a = l != 0 ? atoi(arg) : -1;
1191
1192 /* skip whitespace after the argument */
1193 while (isspace(c))
1194 c = inpc();
1195
1196 if (c != '*' || (c = inpc()) != '/') {
1197 if (keywtab[i].func != linted)
1198 /* extra characters in lint comment */
1199 warning(257);
1200 } else {
1201 /*
1202 * remember that we have already found the end of the
1203 * comment
1204 */
1205 eoc = true;
1206 }
1207
1208 if (keywtab[i].func != NULL)
1209 (*keywtab[i].func)(a);
1210
1211 skip_rest:
1212 while (!eoc) {
1213 lc = c;
1214 if ((c = inpc()) == EOF) {
1215 /* unterminated comment */
1216 error(256);
1217 break;
1218 }
1219 if (lc == '*' && c == '/')
1220 eoc = true;
1221 }
1222 }
1223
1224 /*
1225 * Handle // style comments
1226 */
1227 void
1228 lex_slash_slash_comment(void)
1229 {
1230 int c;
1231
1232 if (!allow_c99 && !allow_gcc)
1233 /* %s does not support // comments */
1234 gnuism(312, allow_c90 ? "C90" : "traditional C");
1235
1236 while ((c = inpc()) != EOF && c != '\n')
1237 continue;
1238 }
1239
1240 /*
1241 * Clear flags for lint comments LINTED, LONGLONG and CONSTCOND.
1242 * clear_warn_flags is called after function definitions and global and
1243 * local declarations and definitions. It is also called between
1244 * the controlling expression and the body of control statements
1245 * (if, switch, for, while).
1246 */
1247 void
1248 clear_warn_flags(void)
1249 {
1250
1251 lwarn = LWARN_ALL;
1252 quadflg = false;
1253 constcond_flag = false;
1254 }
1255
1256 /*
1257 * Strings are stored in a dynamically allocated buffer and passed
1258 * in yylval.y_string to the parser. The parser or the routines called
1259 * by the parser are responsible for freeing this buffer.
1260 */
1261 int
1262 lex_string(void)
1263 {
1264 unsigned char *s;
1265 int c;
1266 size_t len, max;
1267 strg_t *strg;
1268
1269 s = xmalloc(max = 64);
1270
1271 len = 0;
1272 while ((c = get_escaped_char('"')) >= 0) {
1273 /* +1 to reserve space for a trailing NUL character */
1274 if (len + 1 == max)
1275 s = xrealloc(s, max *= 2);
1276 s[len++] = (char)c;
1277 }
1278 s[len] = '\0';
1279 if (c == -2)
1280 /* unterminated string constant */
1281 error(258);
1282
1283 strg = xcalloc(1, sizeof(*strg));
1284 strg->st_char = true;
1285 strg->st_len = len;
1286 strg->st_mem = s;
1287
1288 yylval.y_string = strg;
1289 return T_STRING;
1290 }
1291
1292 int
1293 lex_wide_string(void)
1294 {
1295 char *s;
1296 int c, n;
1297 size_t i, wi;
1298 size_t len, max, wlen;
1299 wchar_t *ws;
1300 strg_t *strg;
1301
1302 s = xmalloc(max = 64);
1303 len = 0;
1304 while ((c = get_escaped_char('"')) >= 0) {
1305 /* +1 to save space for a trailing NUL character */
1306 if (len + 1 >= max)
1307 s = xrealloc(s, max *= 2);
1308 s[len++] = (char)c;
1309 }
1310 s[len] = '\0';
1311 if (c == -2)
1312 /* unterminated string constant */
1313 error(258);
1314
1315 /* get length of wide-character string */
1316 (void)mblen(NULL, 0);
1317 for (i = 0, wlen = 0; i < len; i += n, wlen++) {
1318 if ((n = mblen(&s[i], MB_CUR_MAX)) == -1) {
1319 /* invalid multibyte character */
1320 error(291);
1321 break;
1322 }
1323 if (n == 0)
1324 n = 1;
1325 }
1326
1327 ws = xmalloc((wlen + 1) * sizeof(*ws));
1328
1329 /* convert from multibyte to wide char */
1330 (void)mbtowc(NULL, NULL, 0);
1331 for (i = 0, wi = 0; i < len; i += n, wi++) {
1332 if ((n = mbtowc(&ws[wi], &s[i], MB_CUR_MAX)) == -1)
1333 break;
1334 if (n == 0)
1335 n = 1;
1336 }
1337 ws[wi] = 0;
1338 free(s);
1339
1340 strg = xcalloc(1, sizeof(*strg));
1341 strg->st_char = false;
1342 strg->st_len = wlen;
1343 strg->st_mem = ws;
1344
1345 yylval.y_string = strg;
1346 return T_STRING;
1347 }
1348
1349 void
1350 lex_next_line(void)
1351 {
1352 curr_pos.p_line++;
1353 curr_pos.p_uniq = 0;
1354 debug_step("parsing %s:%d", curr_pos.p_file, curr_pos.p_line);
1355 if (curr_pos.p_file == csrc_pos.p_file) {
1356 csrc_pos.p_line++;
1357 csrc_pos.p_uniq = 0;
1358 }
1359 }
1360
1361 void
1362 lex_unknown_character(int c)
1363 {
1364
1365 /* unknown character \%o */
1366 error(250, c);
1367 }
1368
1369 /*
1370 * The scanner does not create new symbol table entries for symbols it cannot
1371 * find in the symbol table. This is to avoid putting undeclared symbols into
1372 * the symbol table if a syntax error occurs.
1373 *
1374 * getsym is called as soon as it is probably ok to put the symbol in the
1375 * symbol table. It is still possible that symbols are put in the symbol
1376 * table that are not completely declared due to syntax errors. To avoid too
1377 * many problems in this case, symbols get type 'int' in getsym.
1378 *
1379 * XXX calls to getsym should be delayed until declare_1_* is called.
1380 */
1381 sym_t *
1382 getsym(sbuf_t *sb)
1383 {
1384 dinfo_t *di;
1385 char *s;
1386 sym_t *sym;
1387
1388 sym = sb->sb_sym;
1389
1390 /*
1391 * During member declaration it is possible that name() looked
1392 * for symbols of type FVFT, although it should have looked for
1393 * symbols of type FTAG. Same can happen for labels. Both cases
1394 * are compensated here.
1395 */
1396 if (symtyp == FMEMBER || symtyp == FLABEL) {
1397 if (sym == NULL || sym->s_kind == FVFT)
1398 sym = symtab_search(sb);
1399 }
1400
1401 if (sym != NULL) {
1402 lint_assert(sym->s_kind == symtyp);
1403 symtyp = FVFT;
1404 free(sb);
1405 return sym;
1406 }
1407
1408 /* create a new symbol table entry */
1409
1410 /* labels must always be allocated at level 1 (outermost block) */
1411 if (symtyp == FLABEL) {
1412 sym = level_zero_alloc(1, sizeof(*sym));
1413 s = level_zero_alloc(1, sb->sb_len + 1);
1414 (void)memcpy(s, sb->sb_name, sb->sb_len + 1);
1415 sym->s_name = s;
1416 sym->s_block_level = 1;
1417 di = dcs;
1418 while (di->d_enclosing != NULL &&
1419 di->d_enclosing->d_enclosing != NULL)
1420 di = di->d_enclosing;
1421 lint_assert(di->d_kind == DK_AUTO);
1422 } else {
1423 sym = block_zero_alloc(sizeof(*sym));
1424 sym->s_name = sb->sb_name;
1425 sym->s_block_level = block_level;
1426 di = dcs;
1427 }
1428
1429 UNIQUE_CURR_POS(sym->s_def_pos);
1430 if ((sym->s_kind = symtyp) != FLABEL)
1431 sym->s_type = gettyp(INT);
1432
1433 symtyp = FVFT;
1434
1435 symtab_add(sym);
1436
1437 *di->d_ldlsym = sym;
1438 di->d_ldlsym = &sym->s_level_next;
1439
1440 free(sb);
1441 return sym;
1442 }
1443
1444 /*
1445 * Construct a temporary symbol. The symbol name starts with a digit, making
1446 * the name illegal.
1447 */
1448 sym_t *
1449 mktempsym(type_t *tp)
1450 {
1451 static unsigned n = 0;
1452 char *s = level_zero_alloc((size_t)block_level, 64);
1453 sym_t *sym = block_zero_alloc(sizeof(*sym));
1454 scl_t scl;
1455
1456 (void)snprintf(s, 64, "%.8u_tmp", n++);
1457
1458 scl = dcs->d_scl;
1459 if (scl == NOSCL)
1460 scl = block_level > 0 ? AUTO : EXTERN;
1461
1462 sym->s_name = s;
1463 sym->s_type = tp;
1464 sym->s_block_level = block_level;
1465 sym->s_scl = scl;
1466 sym->s_kind = FVFT;
1467 sym->s_used = true;
1468 sym->s_set = true;
1469
1470 symtab_add(sym);
1471
1472 *dcs->d_ldlsym = sym;
1473 dcs->d_ldlsym = &sym->s_level_next;
1474
1475 return sym;
1476 }
1477
1478 /* Remove a symbol forever from the symbol table. */
1479 void
1480 rmsym(sym_t *sym)
1481 {
1482
1483 debug_step("rmsym '%s' %s '%s'",
1484 sym->s_name, symt_name(sym->s_kind), type_name(sym->s_type));
1485 symtab_remove(sym);
1486
1487 /* avoid that the symbol will later be put back to the symbol table */
1488 sym->s_block_level = -1;
1489 }
1490
1491 /*
1492 * Remove all symbols from the symbol table that have the same level as the
1493 * given symbol.
1494 */
1495 void
1496 rmsyms(sym_t *syms)
1497 {
1498 sym_t *sym;
1499
1500 /* Note the use of s_level_next instead of s_symtab_next. */
1501 for (sym = syms; sym != NULL; sym = sym->s_level_next) {
1502 if (sym->s_block_level != -1) {
1503 debug_step("rmsyms '%s' %s '%s'",
1504 sym->s_name, symt_name(sym->s_kind),
1505 type_name(sym->s_type));
1506 symtab_remove(sym);
1507 sym->s_symtab_ref = NULL;
1508 }
1509 }
1510 }
1511
1512 /*
1513 * Put a symbol into the symbol table.
1514 */
1515 void
1516 inssym(int level, sym_t *sym)
1517 {
1518
1519 debug_step("inssym '%s' %s '%s'",
1520 sym->s_name, symt_name(sym->s_kind), type_name(sym->s_type));
1521 symtab_add(sym);
1522 sym->s_block_level = level;
1523
1524 /*
1525 * Placing the inner symbols to the beginning of the list ensures
1526 * that these symbols are preferred over symbols from the outer
1527 * blocks that happen to have the same name.
1528 */
1529 lint_assert(sym->s_symtab_next != NULL
1530 ? sym->s_block_level >= sym->s_symtab_next->s_block_level
1531 : true);
1532 }
1533
1534 /*
1535 * Called at level 0 after syntax errors.
1536 *
1537 * Removes all symbols which are not declared at level 0 from the
1538 * symbol table. Also frees all memory which is not associated with
1539 * level 0.
1540 */
1541 void
1542 clean_up_after_error(void)
1543 {
1544
1545 symtab_remove_locals();
1546
1547 for (size_t i = mem_block_level; i > 0; i--)
1548 level_free_all(i);
1549 }
1550
1551 /* Create a new symbol with the same name as an existing symbol. */
1552 sym_t *
1553 pushdown(const sym_t *sym)
1554 {
1555 sym_t *nsym;
1556
1557 debug_step("pushdown '%s' %s '%s'",
1558 sym->s_name, symt_name(sym->s_kind), type_name(sym->s_type));
1559 nsym = block_zero_alloc(sizeof(*nsym));
1560 lint_assert(sym->s_block_level <= block_level);
1561 nsym->s_name = sym->s_name;
1562 UNIQUE_CURR_POS(nsym->s_def_pos);
1563 nsym->s_kind = sym->s_kind;
1564 nsym->s_block_level = block_level;
1565
1566 symtab_add(nsym);
1567
1568 *dcs->d_ldlsym = nsym;
1569 dcs->d_ldlsym = &nsym->s_level_next;
1570
1571 return nsym;
1572 }
1573
1574 /*
1575 * Free any dynamically allocated memory referenced by
1576 * the value stack or yylval.
1577 * The type of information in yylval is described by tok.
1578 */
1579 void
1580 freeyyv(void *sp, int tok)
1581 {
1582 if (tok == T_NAME || tok == T_TYPENAME) {
1583 sbuf_t *sb = *(sbuf_t **)sp;
1584 free(sb);
1585 } else if (tok == T_CON) {
1586 val_t *val = *(val_t **)sp;
1587 free(val);
1588 } else if (tok == T_STRING) {
1589 strg_t *strg = *(strg_t **)sp;
1590 free(strg->st_mem);
1591 free(strg);
1592 }
1593 }
1594