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