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