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