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