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