Home | History | Annotate | Line # | Download | only in lint1
init.c revision 1.155
      1 /*	$NetBSD: init.c,v 1.155 2021/03/28 10:03:02 rillig Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1994, 1995 Jochen Pohl
      5  * All Rights Reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *      This product includes software developed by Jochen Pohl for
     18  *	The NetBSD Project.
     19  * 4. The name of the author may not be used to endorse or promote products
     20  *    derived from this software without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     32  */
     33 
     34 #if HAVE_NBTOOL_CONFIG_H
     35 #include "nbtool_config.h"
     36 #endif
     37 
     38 #include <sys/cdefs.h>
     39 #if defined(__RCSID) && !defined(lint)
     40 __RCSID("$NetBSD: init.c,v 1.155 2021/03/28 10:03:02 rillig Exp $");
     41 #endif
     42 
     43 #include <stdlib.h>
     44 #include <string.h>
     45 
     46 #include "lint1.h"
     47 
     48 
     49 /*
     50  * Initialization
     51  *
     52  * Handles initializations of global or local objects, like in:
     53  *
     54  *	int number = 12345;
     55  *	int number_with_braces = { 12345 };
     56  *
     57  *	int array_of_unknown_size[] = { 111, 222, 333 };
     58  *	int array_flat[2][2] = { 11, 12, 21, 22 };
     59  *	int array_nested[2][2] = { { 11, 12 }, { 21, 22 } };
     60  *
     61  *	struct { int x, y; } point = { 3, 4 };
     62  *	struct { int x, y; } point = { .y = 4, .x = 3 };
     63  *
     64  * Any scalar expression in the initializer may be surrounded by arbitrarily
     65  * many extra pairs of braces, like in the example 'number_with_braces' (C99
     66  * 6.7.8p11).
     67  *
     68  * For multi-dimensional arrays, the inner braces may be omitted like in
     69  * array_flat or spelled out like in array_nested.
     70  *
     71  * For the initializer, the grammar parser calls these functions:
     72  *
     73  *	begin_initialization
     74  *		init_lbrace			for each '{'
     75  *		designation_add_name		for each '.member' before '='
     76  *		designation_add_subscript	for each '[123]' before '='
     77  *		init_using_expr			for each expression
     78  *		init_rbrace			for each '}'
     79  *	end_initialization
     80  *
     81  * Each '{' begins a new brace level, each '}' ends the current brace level.
     82  * Each brace level has an associated "current object".
     83  *
     84  * Most of the time, the topmost level of brace_level contains a scalar type,
     85  * and its remaining count toggles between 1 and 0.
     86  *
     87  * See also:
     88  *	C99 6.7.8 "Initialization"
     89  *	d_c99_init.c for more examples
     90  */
     91 
     92 
     93 /*
     94  * Describes a single brace level of an ongoing initialization.
     95  *
     96  * XXX: Since C99, the initializers can be listed in arbitrary order by using
     97  * designators to specify the sub-object to be initialized.  The member names
     98  * of non-leaf structs may thus appear repeatedly, as demonstrated in
     99  * d_init_pop_member.c.
    100  *
    101  * See C99 6.7.8, which spans 6 pages full of tricky details and carefully
    102  * selected examples.
    103  */
    104 struct brace_level {
    105 
    106 	/*
    107 	 * The type of the current object that is initialized at this brace
    108 	 * level.
    109 	 *
    110 	 * On the outermost element, this is always NULL since the outermost
    111 	 * initializer-expression may be enclosed in an optional pair of
    112 	 * braces, as of the current implementation.
    113 	 *
    114 	 * FIXME: This approach is wrong.  It's not that the outermost
    115 	 * initializer may be enclosed in additional braces, it's every scalar
    116 	 * that may be enclosed in additional braces, as of C99 6.7.8p11.
    117 	 *
    118 	 * Everywhere else it is nonnull.
    119 	 */
    120 	type_t	*bl_type;
    121 
    122 	/*
    123 	 * The type that will be initialized at the next initialization level,
    124 	 * usually enclosed by another pair of braces.
    125 	 *
    126 	 * For an array, it is the element type, but without 'const'.
    127 	 *
    128 	 * For a struct or union type, it is one of the member types, but
    129 	 * without 'const'.
    130 	 *
    131 	 * The outermost stack element has no bl_type but nevertheless has
    132 	 * bl_subtype.  For example, in 'int var = { 12345 }', initially there
    133 	 * is a brace_level with bl_subtype 'int'.  When the '{' is processed,
    134 	 * an element with bl_type 'int' is pushed to the stack.  When the
    135 	 * corresponding '}' is processed, the inner element is popped again.
    136 	 *
    137 	 * During initialization, only the top 2 elements of the stack are
    138 	 * looked at.
    139 	 *
    140 	 * XXX: Having bl_subtype here is the wrong approach, it should not be
    141 	 * necessary at all; see bl_type.
    142 	 */
    143 	type_t	*bl_subtype;
    144 
    145 	/*
    146 	 * Whether this level of the initializer requires a '}' to be
    147 	 * completed.
    148 	 *
    149 	 * Multidimensional arrays do not need a closing brace to complete
    150 	 * an inner array; for example, { 1, 2, 3, 4 } is a valid initializer
    151 	 * for 'int arr[2][2]'.
    152 	 *
    153 	 * XXX: Double-check whether this is the correct approach at all; see
    154 	 * bl_type.
    155 	 */
    156 	bool bl_brace: 1;
    157 
    158 	/* Whether bl_type is an array of unknown size. */
    159 	bool bl_array_of_unknown_size: 1;
    160 
    161 	/*
    162 	 * XXX: This feels wrong.  Whether or not there has been a named
    163 	 * initializer (called 'designation' since C99) should not matter at
    164 	 * all.  Even after an initializer with designation, counting of the
    165 	 * remaining elements continues, see C99 6.7.8p17.
    166 	 */
    167 	bool bl_seen_named_member: 1;
    168 
    169 	/*
    170 	 * For structs, the next member to be initialized by a designator-less
    171 	 * initializer.
    172 	 */
    173 	sym_t *bl_next_member;
    174 
    175 	/* TODO: Add bl_next_subscript for arrays. */
    176 
    177 	/* TODO: Understand C99 6.7.8p17 and footnote 128 for unions. */
    178 
    179 	/*
    180 	 * The number of remaining elements to be used by expressions without
    181 	 * designator.
    182 	 *
    183 	 * This says nothing about which members have been initialized or not
    184 	 * since starting with C99, members may be initialized in arbitrary
    185 	 * order by using designators.
    186 	 *
    187 	 * For an array of unknown size, this is always 0 and thus irrelevant.
    188 	 *
    189 	 * XXX: for scalars?
    190 	 * XXX: for structs?
    191 	 * XXX: for unions?
    192 	 * XXX: for arrays?
    193 	 *
    194 	 * XXX: Having the count of remaining objects should not be necessary.
    195 	 * It is probably clearer to use bl_next_member and bl_next_subscript
    196 	 * for this purpose.
    197 	 */
    198 	int bl_remaining;
    199 
    200 	/*
    201 	 * The initialization state of the enclosing data structure
    202 	 * (struct, union, array).
    203 	 *
    204 	 * XXX: Or for a scalar, for the top-level element, or for expressions
    205 	 * in redundant braces such as '{{{{ 0 }}}}' (not yet implemented as
    206 	 * of 2021-03-25).
    207 	 */
    208 	struct brace_level *bl_enclosing;
    209 };
    210 
    211 /*
    212  * A single component on the path to the sub-object that is initialized by an
    213  * initializer expression.  Either a struct or union member, or an array
    214  * subscript.
    215  *
    216  * See also: C99 6.7.8 "Initialization"
    217  */
    218 struct designator {
    219 	const char *name;		/* for struct and union */
    220 	/* TODO: add 'subscript' for arrays */
    221 	struct designator *next;
    222 };
    223 
    224 /*
    225  * The optional designation for an initializer, saying which sub-object to
    226  * initialize.  Examples for designations are '.member' or
    227  * '.member[123].member.member[1][1]'.
    228  *
    229  * See also: C99 6.7.8 "Initialization"
    230  */
    231 struct designation {
    232 	struct designator *head;
    233 	struct designator *tail;
    234 };
    235 
    236 struct initialization {
    237 	/*
    238 	 * is set as soon as a fatal error occurred in the initialization.
    239 	 * The effect is that the rest of the initialization is ignored
    240 	 * (parsed by yacc, expression trees built, but no initialization
    241 	 * takes place).
    242 	 */
    243 	bool	initerr;
    244 
    245 	/* The symbol that is to be initialized. */
    246 	sym_t	*initsym;
    247 
    248 	/* The innermost brace level. */
    249 	struct brace_level *brace_level;
    250 
    251 	/*
    252 	 * The C99 designator, if any, for the current initialization
    253 	 * expression.
    254 	 */
    255 	struct designation designation;
    256 
    257 	struct initialization *next;
    258 };
    259 
    260 
    261 static struct initialization *init;
    262 
    263 #ifdef DEBUG
    264 static int debug_ind = 0;
    265 #endif
    266 
    267 
    268 #ifdef DEBUG
    269 
    270 static void __printflike(1, 2)
    271 debug_printf(const char *fmt, ...)
    272 {
    273 	va_list va;
    274 
    275 	va_start(va, fmt);
    276 	vfprintf(stdout, fmt, va);
    277 	va_end(va);
    278 }
    279 
    280 static void
    281 debug_indent(void)
    282 {
    283 	debug_printf("%*s", 2 * debug_ind, "");
    284 }
    285 
    286 static void
    287 debug_enter(const char *func)
    288 {
    289 	printf("%*s+ %s\n", 2 * debug_ind++, "", func);
    290 }
    291 
    292 static void __printflike(1, 2)
    293 debug_step(const char *fmt, ...)
    294 {
    295 	va_list va;
    296 
    297 	debug_indent();
    298 	va_start(va, fmt);
    299 	vfprintf(stdout, fmt, va);
    300 	va_end(va);
    301 	printf("\n");
    302 }
    303 
    304 static void
    305 debug_leave(const char *func)
    306 {
    307 	printf("%*s- %s\n", 2 * --debug_ind, "", func);
    308 }
    309 
    310 #define debug_enter() (debug_enter)(__func__)
    311 #define debug_leave() (debug_leave)(__func__)
    312 
    313 #else
    314 
    315 #define debug_printf(fmt, ...)	do { } while (false)
    316 #define debug_indent()		do { } while (false)
    317 #define debug_enter()		do { } while (false)
    318 #define debug_step(fmt, ...)	do { } while (false)
    319 #define debug_leave()		do { } while (false)
    320 
    321 #endif
    322 
    323 
    324 static struct designator *
    325 designator_new(const char *name)
    326 {
    327 	struct designator *d = xcalloc(1, sizeof *d);
    328 	d->name = name;
    329 	return d;
    330 }
    331 
    332 static void
    333 designator_free(struct designator *d)
    334 {
    335 	free(d);
    336 }
    337 
    338 
    339 #ifdef DEBUG
    340 static void
    341 designation_debug(const struct designation *dn)
    342 {
    343 	const struct designator *p;
    344 
    345 	if (dn->head == NULL)
    346 		return;
    347 
    348 	debug_indent();
    349 	debug_printf("designation: ");
    350 	for (p = dn->head; p != NULL; p = p->next)
    351 		debug_printf(".%s", p->name);
    352 	debug_printf("\n");
    353 }
    354 #else
    355 #define designation_debug(dn) do { } while (false)
    356 #endif
    357 
    358 static void
    359 designation_add(struct designation *dn, struct designator *dr)
    360 {
    361 
    362 	if (dn->head != NULL) {
    363 		dn->tail->next = dr;
    364 		dn->tail = dr;
    365 	} else {
    366 		dn->head = dr;
    367 		dn->tail = dr;
    368 	}
    369 
    370 	designation_debug(dn);
    371 }
    372 
    373 /* TODO: add support for array subscripts, not only named members */
    374 /*
    375  * TODO: This function should not be necessary at all.  There is no need to
    376  *  remove the head of the list.
    377  */
    378 static void
    379 designation_shift_level(struct designation *dn)
    380 {
    381 	lint_assert(dn->head != NULL);
    382 
    383 	if (dn->head == dn->tail) {
    384 		designator_free(dn->head);
    385 		dn->head = NULL;
    386 		dn->tail = NULL;
    387 	} else {
    388 		struct designator *head = dn->head;
    389 		dn->head = dn->head->next;
    390 		designator_free(head);
    391 	}
    392 
    393 	designation_debug(dn);
    394 }
    395 
    396 
    397 static struct brace_level *
    398 brace_level_new(type_t *type, type_t *subtype, int remaining)
    399 {
    400 	struct brace_level *level = xcalloc(1, sizeof(*level));
    401 
    402 	level->bl_type = type;
    403 	level->bl_subtype = subtype;
    404 	level->bl_remaining = remaining;
    405 
    406 	return level;
    407 }
    408 
    409 static void
    410 brace_level_free(struct brace_level *level)
    411 {
    412 	free(level);
    413 }
    414 
    415 #ifdef DEBUG
    416 /*
    417  * TODO: only log the top of the stack after each modifying operation
    418  *
    419  * TODO: wrap all write accesses to brace_level in setter functions
    420  */
    421 static void
    422 brace_level_debug(const struct brace_level *level)
    423 {
    424 	if (level->bl_type != NULL)
    425 		debug_printf("type '%s'", type_name(level->bl_type));
    426 	if (level->bl_type != NULL && level->bl_subtype != NULL)
    427 		debug_printf(", ");
    428 	if (level->bl_subtype != NULL)
    429 		debug_printf("subtype '%s'", type_name(level->bl_subtype));
    430 
    431 	if (level->bl_brace)
    432 		debug_printf(", needs closing brace");
    433 	if (level->bl_array_of_unknown_size)
    434 		debug_printf(", array of unknown size");
    435 	if (level->bl_seen_named_member)
    436 		debug_printf(", seen named member");
    437 
    438 	const type_t *eff_type = level->bl_type != NULL
    439 	    ? level->bl_type : level->bl_subtype;
    440 	if (eff_type->t_tspec == STRUCT && level->bl_next_member != NULL)
    441 		debug_printf(", next member '%s'",
    442 		    level->bl_next_member->s_name);
    443 
    444 	debug_printf(", remaining %d\n", level->bl_remaining);
    445 }
    446 #else
    447 #define brace_level_debug(level) do { } while (false)
    448 #endif
    449 
    450 static void
    451 brace_level_set_array_dimension(struct brace_level *level, int dim)
    452 {
    453 	debug_step("setting the array size to %d", dim);
    454 	level->bl_type->t_dim = dim;
    455 	debug_indent();
    456 	brace_level_debug(level);
    457 }
    458 
    459 static void
    460 brace_level_next_member(struct brace_level *level)
    461 {
    462 	const sym_t *m;
    463 
    464 	do {
    465 		m = level->bl_next_member = level->bl_next_member->s_next;
    466 		/* XXX: can this assertion be made to fail? */
    467 		lint_assert(m != NULL);
    468 	} while (m->s_bitfield && m->s_name == unnamed);
    469 
    470 	debug_indent();
    471 	brace_level_debug(level);
    472 }
    473 
    474 static const sym_t *
    475 brace_level_look_up_member(const struct brace_level *level, const char *name)
    476 {
    477 	const type_t *tp = level->bl_type;
    478 	const sym_t *m;
    479 
    480 	lint_assert(tp->t_tspec == STRUCT || tp->t_tspec == UNION);
    481 
    482 	for (m = tp->t_str->sou_first_member; m != NULL; m = m->s_next) {
    483 		if (m->s_bitfield && m->s_name == unnamed)
    484 			continue;
    485 		if (strcmp(m->s_name, name) == 0)
    486 			return m;
    487 	}
    488 
    489 	return NULL;
    490 }
    491 
    492 /* TODO: merge duplicate code */
    493 static sym_t *
    494 brace_level_look_up_member_bloated(struct brace_level *level,
    495 			   const struct designator *dr, int *count)
    496 {
    497 	sym_t *m;
    498 
    499 	for (m = level->bl_type->t_str->sou_first_member;
    500 	     m != NULL; m = m->s_next) {
    501 		if (m->s_bitfield && m->s_name == unnamed)
    502 			continue;
    503 		/*
    504 		 * TODO: split into separate functions:
    505 		 *
    506 		 * look_up_array_next
    507 		 * look_up_array_designator
    508 		 * look_up_struct_next
    509 		 * look_up_struct_designator
    510 		 */
    511 		if (dr != NULL) {
    512 			/* XXX: this log entry looks unnecessarily verbose */
    513 			debug_step("have member '%s', want member '%s'",
    514 			    m->s_name, dr->name);
    515 			if (strcmp(m->s_name, dr->name) == 0) {
    516 				(*count)++;
    517 				break;
    518 			} else
    519 				continue;
    520 		}
    521 
    522 		/* XXX: What is this code for? */
    523 		if (++(*count) == 1) {
    524 			level->bl_next_member = m;
    525 			level->bl_subtype = m->s_type;
    526 		}
    527 	}
    528 
    529 	return m;
    530 }
    531 
    532 /* TODO: document me */
    533 /* TODO: think of a better name than 'push' */
    534 static bool
    535 brace_level_push_array(struct brace_level *level)
    536 {
    537 	if (level->bl_enclosing->bl_seen_named_member) {
    538 		level->bl_brace = true;
    539 		debug_step("ARRAY, seen named member, needs closing brace");
    540 	}
    541 
    542 	if (is_incomplete(level->bl_type) &&
    543 	    level->bl_enclosing->bl_enclosing != NULL) {
    544 		/* initialization of an incomplete type */
    545 		error(175);
    546 		return false;
    547 	}
    548 
    549 	level->bl_subtype = level->bl_type->t_subt;
    550 	level->bl_array_of_unknown_size = is_incomplete(level->bl_type);
    551 	level->bl_remaining = level->bl_type->t_dim;
    552 	debug_step("type '%s' remaining %d",
    553 	    type_name(level->bl_type), level->bl_remaining);
    554 	return true;
    555 }
    556 
    557 
    558 static struct initialization *
    559 initialization_new(sym_t *sym)
    560 {
    561 	struct initialization *in = xcalloc(1, sizeof(*in));
    562 
    563 	in->initsym = sym;
    564 
    565 	return in;
    566 }
    567 
    568 static void
    569 initialization_free(struct initialization *in)
    570 {
    571 	struct brace_level *level, *next;
    572 
    573 	for (level = in->brace_level; level != NULL; level = next) {
    574 		next = level->bl_enclosing;
    575 		brace_level_free(level);
    576 	}
    577 
    578 	free(in);
    579 }
    580 
    581 #ifdef DEBUG
    582 /*
    583  * TODO: only call debug_initstack after each push/pop.
    584  */
    585 static void
    586 initialization_debug(const struct initialization *in)
    587 {
    588 	if (in->brace_level == NULL) {
    589 		debug_step("no brace level in the current initialization");
    590 		return;
    591 	}
    592 
    593 	size_t i = 0;
    594 	for (const struct brace_level *level = in->brace_level;
    595 	     level != NULL; level = level->bl_enclosing) {
    596 		debug_indent();
    597 		debug_printf("brace level %zu: ", i);
    598 		brace_level_debug(level);
    599 		i++;
    600 	}
    601 }
    602 #else
    603 #define initialization_debug(in) do { } while (false)
    604 #endif
    605 
    606 static void
    607 initialization_set_error(struct initialization *in)
    608 {
    609 	in->initerr = true;
    610 }
    611 
    612 /* XXX: unnecessary prototype since it is not recursive */
    613 static	bool	init_array_using_string(struct initialization *, tnode_t *);
    614 
    615 
    616 static struct initialization *
    617 current_init(void)
    618 {
    619 	lint_assert(init != NULL);
    620 	return init;
    621 }
    622 
    623 bool *
    624 current_initerr(void)
    625 {
    626 	return &current_init()->initerr;
    627 }
    628 
    629 sym_t **
    630 current_initsym(void)
    631 {
    632 	return &current_init()->initsym;
    633 }
    634 
    635 #define initsym		(*current_initsym())
    636 
    637 
    638 void
    639 begin_initialization(sym_t *sym)
    640 {
    641 	struct initialization *in;
    642 
    643 	debug_step("begin initialization of '%s'", type_name(sym->s_type));
    644 	in = initialization_new(sym);
    645 	in->next = init;
    646 	init = in;
    647 }
    648 
    649 void
    650 end_initialization(void)
    651 {
    652 	struct initialization *in;
    653 
    654 	in = init;
    655 	init = init->next;
    656 	initialization_free(in);
    657 	debug_step("end initialization");
    658 }
    659 
    660 
    661 
    662 void
    663 designation_add_name(sbuf_t *sb)
    664 {
    665 	designation_add(&current_init()->designation,
    666 	    designator_new(sb->sb_name));
    667 }
    668 
    669 /* TODO: Move the function body up here, to avoid the forward declaration. */
    670 static void initstack_pop_nobrace(struct initialization *);
    671 
    672 /*
    673  * A sub-object of an array is initialized using a designator.  This does not
    674  * have to be an array element directly, it can also be used to initialize
    675  * only a sub-object of the array element.
    676  *
    677  * C99 example: struct { int member[4]; } var = { [2] = 12345 };
    678  *
    679  * GNU example: struct { int member[4]; } var = { [1 ... 3] = 12345 };
    680  *
    681  * TODO: test the following initialization with an outer and an inner type:
    682  *
    683  * .deeply[0].nested = {
    684  *	.deeply[1].nested = {
    685  *		12345,
    686  *	},
    687  * }
    688  */
    689 void
    690 designation_add_subscript(range_t range)
    691 {
    692 	struct initialization *in = current_init();
    693 	struct brace_level *level;
    694 
    695 	debug_enter();
    696 	if (range.lo == range.hi)
    697 		debug_step("subscript is %zu", range.hi);
    698 	else
    699 		debug_step("subscript range is %zu ... %zu",
    700 		    range.lo, range.hi);
    701 
    702 	/* XXX: This call is wrong here, it must be somewhere else. */
    703 	initstack_pop_nobrace(in);
    704 
    705 	level = in->brace_level;
    706 	if (level->bl_array_of_unknown_size) {
    707 		/* No +1 here, extend_if_array_of_unknown_size will add it. */
    708 		int auto_dim = (int)range.hi;
    709 		if (auto_dim > level->bl_type->t_dim)
    710 			brace_level_set_array_dimension(level, auto_dim);
    711 	}
    712 
    713 	debug_leave();
    714 }
    715 
    716 
    717 /*
    718  * Initialize the initialization stack by putting an entry for the object
    719  * which is to be initialized on it.
    720  *
    721  * TODO: merge into begin_initialization
    722  */
    723 void
    724 initstack_init(void)
    725 {
    726 	struct initialization *in = current_init();
    727 
    728 	if (in->initerr)
    729 		return;
    730 
    731 	debug_enter();
    732 
    733 	/*
    734 	 * If the type which is to be initialized is an incomplete array,
    735 	 * it must be duplicated.
    736 	 */
    737 	if (initsym->s_type->t_tspec == ARRAY && is_incomplete(initsym->s_type))
    738 		initsym->s_type = duptyp(initsym->s_type);
    739 	/* TODO: does 'duptyp' create a memory leak? */
    740 
    741 	in->brace_level = brace_level_new(NULL, initsym->s_type, 1);
    742 
    743 	initialization_debug(in);
    744 	debug_leave();
    745 }
    746 
    747 /* TODO: document me */
    748 static void
    749 initstack_pop_item_named_member(struct initialization *in, const char *name)
    750 {
    751 	struct brace_level *level = in->brace_level;
    752 	const sym_t *m;
    753 
    754 	/*
    755 	 * TODO: fix wording of the debug message; this doesn't seem to be
    756 	 * related to initializing the named member.
    757 	 */
    758 	debug_step("initializing named member '%s'", name);
    759 
    760 	if (level->bl_type->t_tspec != STRUCT &&
    761 	    level->bl_type->t_tspec != UNION) {
    762 		/* syntax error '%s' */
    763 		error(249, "named member must only be used with struct/union");
    764 		initialization_set_error(in);
    765 		return;
    766 	}
    767 
    768 	m = brace_level_look_up_member(level, name);
    769 	if (m == NULL) {
    770 		/* TODO: add type information to the message */
    771 		/* undefined struct/union member: %s */
    772 		error(101, name);
    773 
    774 		designation_shift_level(&in->designation);
    775 		level->bl_seen_named_member = true;
    776 		return;
    777 	}
    778 
    779 	debug_step("found matching member");
    780 	level->bl_subtype = m->s_type;
    781 	/* XXX: why ++? */
    782 	level->bl_remaining++;
    783 	/* XXX: why is bl_seen_named_member not set? */
    784 	designation_shift_level(&in->designation);
    785 }
    786 
    787 /* TODO: think of a better name than 'pop' */
    788 static void
    789 initstack_pop_item_unnamed(struct initialization *in)
    790 {
    791 	struct brace_level *level = in->brace_level;
    792 
    793 	/*
    794 	 * If the removed element was a structure member, we must go
    795 	 * to the next structure member.
    796 	 */
    797 	if (level->bl_remaining > 0 && level->bl_type->t_tspec == STRUCT &&
    798 	    !level->bl_seen_named_member) {
    799 		brace_level_next_member(level);
    800 		level->bl_subtype = level->bl_next_member->s_type;
    801 	}
    802 }
    803 
    804 /* TODO: think of a better name than 'pop' */
    805 static void
    806 initstack_pop_item(struct initialization *in)
    807 {
    808 	struct brace_level *level;
    809 
    810 	debug_enter();
    811 
    812 	level = in->brace_level;
    813 	debug_indent();
    814 	debug_printf("popping: ");
    815 	brace_level_debug(level);
    816 
    817 	in->brace_level = level->bl_enclosing;
    818 	brace_level_free(level);
    819 	level = in->brace_level;
    820 	lint_assert(level != NULL);
    821 
    822 	level->bl_remaining--;
    823 	lint_assert(level->bl_remaining >= 0);
    824 	debug_step("%d elements remaining", level->bl_remaining);
    825 
    826 	if (in->designation.head != NULL && in->designation.head->name != NULL)
    827 		initstack_pop_item_named_member(in, in->designation.head->name);
    828 	else
    829 		initstack_pop_item_unnamed(in);
    830 
    831 	initialization_debug(in);
    832 	debug_leave();
    833 }
    834 
    835 /*
    836  * Take all entries, including the first which requires a closing brace,
    837  * from the stack.
    838  */
    839 static void
    840 initstack_pop_brace(struct initialization *in)
    841 {
    842 	bool brace;
    843 
    844 	debug_enter();
    845 	initialization_debug(in);
    846 	do {
    847 		brace = in->brace_level->bl_brace;
    848 		/* TODO: improve wording of the debug message */
    849 		debug_step("loop brace=%d", brace);
    850 		initstack_pop_item(in);
    851 	} while (!brace);
    852 	initialization_debug(in);
    853 	debug_leave();
    854 }
    855 
    856 /*
    857  * Take all entries which cannot be used for further initializers from the
    858  * stack, but do this only if they do not require a closing brace.
    859  */
    860 /* TODO: think of a better name than 'pop' */
    861 static void
    862 initstack_pop_nobrace(struct initialization *in)
    863 {
    864 
    865 	debug_enter();
    866 	while (!in->brace_level->bl_brace &&
    867 	       in->brace_level->bl_remaining == 0 &&
    868 	       !in->brace_level->bl_array_of_unknown_size)
    869 		initstack_pop_item(in);
    870 	debug_leave();
    871 }
    872 
    873 /* Extend an array of unknown size by one element */
    874 static void
    875 extend_if_array_of_unknown_size(struct initialization *in)
    876 {
    877 	struct brace_level *level = in->brace_level;
    878 
    879 	if (level->bl_remaining != 0)
    880 		return;
    881 	/*
    882 	 * XXX: According to the function name, there should be a 'return' if
    883 	 * bl_array_of_unknown_size is false.  There's probably a test missing
    884 	 * for that case.
    885 	 */
    886 
    887 	/*
    888 	 * The only place where an incomplete array may appear is at the
    889 	 * outermost aggregate level of the object to be initialized.
    890 	 */
    891 	lint_assert(level->bl_enclosing->bl_enclosing == NULL);
    892 	lint_assert(level->bl_type->t_tspec == ARRAY);
    893 
    894 	debug_step("extending array of unknown size '%s'",
    895 	    type_name(level->bl_type));
    896 	level->bl_remaining = 1;
    897 	level->bl_type->t_dim++;
    898 	setcomplete(level->bl_type, true);
    899 
    900 	debug_step("extended type is '%s'", type_name(level->bl_type));
    901 }
    902 
    903 
    904 
    905 /* TODO: document me */
    906 /* TODO: think of a better name than 'push' */
    907 static bool
    908 initstack_push_struct_or_union(struct initialization *in)
    909 {
    910 	/*
    911 	 * TODO: remove unnecessary 'const' for variables in functions that
    912 	 * fit on a single screen.  Keep it for larger functions.
    913 	 */
    914 	struct brace_level *level = in->brace_level;
    915 	int cnt;
    916 	sym_t *m;
    917 
    918 	if (is_incomplete(level->bl_type)) {
    919 		/* initialization of an incomplete type */
    920 		error(175);
    921 		initialization_set_error(in);
    922 		return false;
    923 	}
    924 
    925 	cnt = 0;
    926 	designation_debug(&in->designation);
    927 	debug_step("lookup for '%s'%s",
    928 	    type_name(level->bl_type),
    929 	    level->bl_seen_named_member ? ", seen named member" : "");
    930 
    931 	m = brace_level_look_up_member_bloated(level,
    932 	    in->designation.head, &cnt);
    933 
    934 	if (in->designation.head != NULL) {
    935 		if (m == NULL) {
    936 			debug_step("pop struct");
    937 			return true;
    938 		}
    939 		level->bl_next_member = m;
    940 		level->bl_subtype = m->s_type;
    941 		level->bl_seen_named_member = true;
    942 		debug_step("named member '%s'",
    943 		    in->designation.head->name);
    944 		designation_shift_level(&in->designation);
    945 		cnt = level->bl_type->t_tspec == STRUCT ? 2 : 1;
    946 	}
    947 	level->bl_brace = true;
    948 	debug_step("unnamed element with type '%s'%s",
    949 	    type_name(
    950 		level->bl_type != NULL ? level->bl_type : level->bl_subtype),
    951 	    level->bl_brace ? ", needs closing brace" : "");
    952 	if (cnt == 0) {
    953 		/* cannot init. struct/union with no named member */
    954 		error(179);
    955 		initialization_set_error(in);
    956 		return false;
    957 	}
    958 	level->bl_remaining = level->bl_type->t_tspec == STRUCT ? cnt : 1;
    959 	return false;
    960 }
    961 
    962 /* TODO: document me */
    963 /* TODO: think of a better name than 'push' */
    964 static void
    965 initstack_push(struct initialization *in)
    966 {
    967 	struct brace_level *level, *enclosing;
    968 
    969 	debug_enter();
    970 
    971 	extend_if_array_of_unknown_size(in);
    972 
    973 	level = in->brace_level;
    974 	lint_assert(level->bl_remaining > 0);
    975 	lint_assert(level->bl_type == NULL ||
    976 	    !is_scalar(level->bl_type->t_tspec));
    977 
    978 	in->brace_level = xcalloc(1, sizeof *in->brace_level);
    979 	in->brace_level->bl_enclosing = level;
    980 	in->brace_level->bl_type = level->bl_subtype;
    981 	lint_assert(in->brace_level->bl_type->t_tspec != FUNC);
    982 
    983 again:
    984 	level = in->brace_level;
    985 
    986 	debug_step("expecting type '%s'", type_name(level->bl_type));
    987 	lint_assert(level->bl_type != NULL);
    988 	switch (level->bl_type->t_tspec) {
    989 	case ARRAY:
    990 		if (in->designation.head != NULL) {
    991 			debug_step("pop array, named member '%s'%s",
    992 			    in->designation.head->name,
    993 			    level->bl_brace ? ", needs closing brace" : "");
    994 			goto pop;
    995 		}
    996 
    997 		if (!brace_level_push_array(level))
    998 			initialization_set_error(in);
    999 		break;
   1000 
   1001 	case UNION:
   1002 		if (tflag)
   1003 			/* initialization of union is illegal in trad. C */
   1004 			warning(238);
   1005 		/* FALLTHROUGH */
   1006 	case STRUCT:
   1007 		if (initstack_push_struct_or_union(in))
   1008 			goto pop;
   1009 		break;
   1010 	default:
   1011 		if (in->designation.head != NULL) {
   1012 			debug_step("pop scalar");
   1013 	pop:
   1014 			/* TODO: extract this into end_initializer_level */
   1015 			enclosing = in->brace_level->bl_enclosing;
   1016 			brace_level_free(level);
   1017 			in->brace_level = enclosing;
   1018 			goto again;
   1019 		}
   1020 		/* The initialization stack now expects a single scalar. */
   1021 		level->bl_remaining = 1;
   1022 		break;
   1023 	}
   1024 
   1025 	initialization_debug(in);
   1026 	debug_leave();
   1027 }
   1028 
   1029 static void
   1030 check_too_many_initializers(struct initialization *in)
   1031 {
   1032 	const struct brace_level *level = in->brace_level;
   1033 
   1034 	if (level->bl_remaining > 0)
   1035 		return;
   1036 	/*
   1037 	 * FIXME: even with named members, there can be too many initializers
   1038 	 */
   1039 	if (level->bl_array_of_unknown_size || level->bl_seen_named_member)
   1040 		return;
   1041 
   1042 	tspec_t t = level->bl_type->t_tspec;
   1043 	if (t == ARRAY) {
   1044 		/* too many array initializers, expected %d */
   1045 		error(173, level->bl_type->t_dim);
   1046 	} else if (t == STRUCT || t == UNION) {
   1047 		/* too many struct/union initializers */
   1048 		error(172);
   1049 	} else {
   1050 		/* too many initializers */
   1051 		error(174);
   1052 	}
   1053 	initialization_set_error(in);
   1054 }
   1055 
   1056 /*
   1057  * Process a '{' in an initializer by starting the initialization of the
   1058  * nested data structure, with bl_type being the bl_subtype of the outer
   1059  * initialization level.
   1060  */
   1061 static void
   1062 initstack_next_brace(struct initialization *in)
   1063 {
   1064 
   1065 	debug_enter();
   1066 	initialization_debug(in);
   1067 
   1068 	if (in->brace_level->bl_type != NULL &&
   1069 	    is_scalar(in->brace_level->bl_type->t_tspec)) {
   1070 		/* invalid initializer type %s */
   1071 		error(176, type_name(in->brace_level->bl_type));
   1072 		initialization_set_error(in);
   1073 	}
   1074 	if (!in->initerr)
   1075 		check_too_many_initializers(in);
   1076 	if (!in->initerr)
   1077 		initstack_push(in);
   1078 	if (!in->initerr) {
   1079 		in->brace_level->bl_brace = true;
   1080 		designation_debug(&in->designation);
   1081 		debug_step("expecting type '%s'",
   1082 		    type_name(in->brace_level->bl_type != NULL
   1083 			? in->brace_level->bl_type
   1084 			: in->brace_level->bl_subtype));
   1085 	}
   1086 
   1087 	initialization_debug(in);
   1088 	debug_leave();
   1089 }
   1090 
   1091 /* TODO: document me, or think of a better name */
   1092 static void
   1093 initstack_next_nobrace(struct initialization *in, tnode_t *tn)
   1094 {
   1095 	debug_enter();
   1096 
   1097 	if (in->brace_level->bl_type == NULL &&
   1098 	    !is_scalar(in->brace_level->bl_subtype->t_tspec)) {
   1099 		/* {}-enclosed initializer required */
   1100 		error(181);
   1101 		/* XXX: maybe set initerr here */
   1102 	}
   1103 
   1104 	if (!in->initerr)
   1105 		check_too_many_initializers(in);
   1106 
   1107 	while (!in->initerr) {
   1108 		struct brace_level *level = in->brace_level;
   1109 
   1110 		if (tn->tn_type->t_tspec == STRUCT &&
   1111 		    level->bl_type == tn->tn_type &&
   1112 		    level->bl_enclosing != NULL &&
   1113 		    level->bl_enclosing->bl_enclosing != NULL) {
   1114 			level->bl_brace = false;
   1115 			level->bl_remaining = 1; /* the struct itself */
   1116 			break;
   1117 		}
   1118 
   1119 		if (level->bl_type != NULL &&
   1120 		    is_scalar(level->bl_type->t_tspec))
   1121 			break;
   1122 		initstack_push(in);
   1123 	}
   1124 
   1125 	initialization_debug(in);
   1126 	debug_leave();
   1127 }
   1128 
   1129 /* TODO: document me */
   1130 void
   1131 init_lbrace(void)
   1132 {
   1133 	struct initialization *in = current_init();
   1134 
   1135 	if (in->initerr)
   1136 		return;
   1137 
   1138 	debug_enter();
   1139 	initialization_debug(in);
   1140 
   1141 	if ((initsym->s_scl == AUTO || initsym->s_scl == REG) &&
   1142 	    in->brace_level->bl_enclosing == NULL) {
   1143 		if (tflag &&
   1144 		    !is_scalar(in->brace_level->bl_subtype->t_tspec))
   1145 			/* no automatic aggregate initialization in trad. C */
   1146 			warning(188);
   1147 	}
   1148 
   1149 	/*
   1150 	 * Remove all entries which cannot be used for further initializers
   1151 	 * and do not expect a closing brace.
   1152 	 */
   1153 	initstack_pop_nobrace(in);
   1154 
   1155 	initstack_next_brace(in);
   1156 
   1157 	initialization_debug(in);
   1158 	debug_leave();
   1159 }
   1160 
   1161 /*
   1162  * Process a '}' in an initializer by finishing the current level of the
   1163  * initialization stack.
   1164  */
   1165 void
   1166 init_rbrace(void)
   1167 {
   1168 	struct initialization *in = current_init();
   1169 
   1170 	if (in->initerr)
   1171 		return;
   1172 
   1173 	debug_enter();
   1174 	initstack_pop_brace(in);
   1175 	debug_leave();
   1176 }
   1177 
   1178 /* In traditional C, bit-fields can be initialized only by integer constants. */
   1179 static void
   1180 check_bit_field_init(const tnode_t *ln, tspec_t lt, tspec_t rt)
   1181 {
   1182 	if (tflag &&
   1183 	    is_integer(lt) &&
   1184 	    ln->tn_type->t_bitfield &&
   1185 	    !is_integer(rt)) {
   1186 		/* bit-field initialization is illegal in traditional C */
   1187 		warning(186);
   1188 	}
   1189 }
   1190 
   1191 static void
   1192 check_non_constant_initializer(const tnode_t *tn, scl_t sclass)
   1193 {
   1194 	/* TODO: rename CON to CONSTANT to avoid ambiguity with CONVERT */
   1195 	if (tn == NULL || tn->tn_op == CON)
   1196 		return;
   1197 
   1198 	sym_t *sym;
   1199 	ptrdiff_t offs;
   1200 	if (constant_addr(tn, &sym, &offs))
   1201 		return;
   1202 
   1203 	if (sclass == AUTO || sclass == REG) {
   1204 		/* non-constant initializer */
   1205 		c99ism(177);
   1206 	} else {
   1207 		/* non-constant initializer */
   1208 		error(177);
   1209 	}
   1210 }
   1211 
   1212 /*
   1213  * Initialize a non-array object with automatic storage duration and only a
   1214  * single initializer expression without braces by delegating to ASSIGN.
   1215  */
   1216 static bool
   1217 init_using_assign(struct initialization *in, tnode_t *rn)
   1218 {
   1219 	tnode_t *ln, *tn;
   1220 
   1221 	if (initsym->s_type->t_tspec == ARRAY)
   1222 		return false;
   1223 	if (in->brace_level->bl_enclosing != NULL)
   1224 		return false;
   1225 
   1226 	debug_step("handing over to ASSIGN");
   1227 
   1228 	ln = new_name_node(initsym, 0);
   1229 	ln->tn_type = tduptyp(ln->tn_type);
   1230 	ln->tn_type->t_const = false;
   1231 
   1232 	tn = build(ASSIGN, ln, rn);
   1233 	expr(tn, false, false, false, false);
   1234 
   1235 	/* XXX: why not clean up the initstack here already? */
   1236 	return true;
   1237 }
   1238 
   1239 static void
   1240 check_init_expr(struct initialization *in, tnode_t *tn, scl_t sclass)
   1241 {
   1242 	tnode_t *ln;
   1243 	tspec_t lt, rt;
   1244 	struct mbl *tmem;
   1245 
   1246 	/* Create a temporary node for the left side. */
   1247 	ln = tgetblk(sizeof *ln);
   1248 	ln->tn_op = NAME;
   1249 	ln->tn_type = tduptyp(in->brace_level->bl_type);
   1250 	ln->tn_type->t_const = false;
   1251 	ln->tn_lvalue = true;
   1252 	ln->tn_sym = initsym;		/* better than nothing */
   1253 
   1254 	tn = cconv(tn);
   1255 
   1256 	lt = ln->tn_type->t_tspec;
   1257 	rt = tn->tn_type->t_tspec;
   1258 
   1259 	debug_step("typeok '%s', '%s'",
   1260 	    type_name(ln->tn_type), type_name(tn->tn_type));
   1261 	if (!typeok(INIT, 0, ln, tn))
   1262 		return;
   1263 
   1264 	/*
   1265 	 * Preserve the tree memory. This is necessary because otherwise
   1266 	 * expr() would free it.
   1267 	 */
   1268 	tmem = tsave();
   1269 	expr(tn, true, false, true, false);
   1270 	trestor(tmem);
   1271 
   1272 	check_bit_field_init(ln, lt, rt);
   1273 
   1274 	/*
   1275 	 * XXX: Is it correct to do this conversion _after_ the typeok above?
   1276 	 */
   1277 	if (lt != rt ||
   1278 	    (in->brace_level->bl_type->t_bitfield && tn->tn_op == CON))
   1279 		tn = convert(INIT, 0, in->brace_level->bl_type, tn);
   1280 
   1281 	check_non_constant_initializer(tn, sclass);
   1282 }
   1283 
   1284 void
   1285 init_using_expr(tnode_t *tn)
   1286 {
   1287 	struct initialization *in = current_init();
   1288 	scl_t	sclass;
   1289 
   1290 	debug_enter();
   1291 	initialization_debug(in);
   1292 	designation_debug(&in->designation);
   1293 	debug_step("expr:");
   1294 	debug_node(tn, debug_ind + 1);
   1295 
   1296 	if (in->initerr || tn == NULL)
   1297 		goto done;
   1298 
   1299 	sclass = initsym->s_scl;
   1300 	if ((sclass == AUTO || sclass == REG) && init_using_assign(in, tn))
   1301 		goto done;
   1302 
   1303 	initstack_pop_nobrace(in);
   1304 
   1305 	if (init_array_using_string(in, tn)) {
   1306 		debug_step("after initializing the string:");
   1307 		/* XXX: why not clean up the initstack here already? */
   1308 		goto done_initstack;
   1309 	}
   1310 
   1311 	initstack_next_nobrace(in, tn);
   1312 	if (in->initerr || tn == NULL)
   1313 		goto done_initstack;
   1314 
   1315 	in->brace_level->bl_remaining--;
   1316 	debug_step("%d elements remaining", in->brace_level->bl_remaining);
   1317 
   1318 	check_init_expr(in, tn, sclass);
   1319 
   1320 done_initstack:
   1321 	initialization_debug(in);
   1322 
   1323 done:
   1324 	while (in->designation.head != NULL)
   1325 		designation_shift_level(&in->designation);
   1326 
   1327 	debug_leave();
   1328 }
   1329 
   1330 
   1331 /* Initialize a character array or wchar_t array with a string literal. */
   1332 static bool
   1333 init_array_using_string(struct initialization *in, tnode_t *tn)
   1334 {
   1335 	tspec_t	t;
   1336 	struct brace_level *level;
   1337 	int	len;
   1338 	strg_t	*strg;
   1339 
   1340 	if (tn->tn_op != STRING)
   1341 		return false;
   1342 
   1343 	debug_enter();
   1344 	initialization_debug(in);
   1345 
   1346 	level = in->brace_level;
   1347 	strg = tn->tn_string;
   1348 
   1349 	/*
   1350 	 * Check if we have an array type which can be initialized by
   1351 	 * the string.
   1352 	 */
   1353 	if (level->bl_subtype != NULL && level->bl_subtype->t_tspec == ARRAY) {
   1354 		debug_step("subt array");
   1355 		t = level->bl_subtype->t_subt->t_tspec;
   1356 		if (!((strg->st_tspec == CHAR &&
   1357 		       (t == CHAR || t == UCHAR || t == SCHAR)) ||
   1358 		      (strg->st_tspec == WCHAR && t == WCHAR))) {
   1359 			debug_leave();
   1360 			return false;
   1361 		}
   1362 		/* XXX: duplicate code, see below */
   1363 
   1364 		/* Put the array at top of stack */
   1365 		initstack_push(in);
   1366 		level = in->brace_level;
   1367 
   1368 		/* TODO: what if both bl_type and bl_subtype are ARRAY? */
   1369 
   1370 	} else if (level->bl_type != NULL && level->bl_type->t_tspec == ARRAY) {
   1371 		debug_step("type array");
   1372 		t = level->bl_type->t_subt->t_tspec;
   1373 		if (!((strg->st_tspec == CHAR &&
   1374 		       (t == CHAR || t == UCHAR || t == SCHAR)) ||
   1375 		      (strg->st_tspec == WCHAR && t == WCHAR))) {
   1376 			debug_leave();
   1377 			return false;
   1378 		}
   1379 		/* XXX: duplicate code, see above */
   1380 
   1381 		/*
   1382 		 * TODO: is this really not needed in the branch above this
   1383 		 * one?
   1384 		 */
   1385 		/*
   1386 		 * If the array is already partly initialized, we are
   1387 		 * wrong here.
   1388 		 */
   1389 		if (level->bl_remaining != level->bl_type->t_dim) {
   1390 			debug_leave();
   1391 			return false;
   1392 		}
   1393 	} else {
   1394 		debug_leave();
   1395 		return false;
   1396 	}
   1397 
   1398 	/* Get length without trailing NUL character. */
   1399 	len = strg->st_len;
   1400 
   1401 	if (level->bl_array_of_unknown_size) {
   1402 		level->bl_array_of_unknown_size = false;
   1403 		level->bl_type->t_dim = len + 1;
   1404 		setcomplete(level->bl_type, true);
   1405 	} else {
   1406 		/*
   1407 		 * TODO: check for buffer overflow in the object to be
   1408 		 * initialized
   1409 		 */
   1410 		/* XXX: double-check for off-by-one error */
   1411 		if (level->bl_type->t_dim < len) {
   1412 			/* non-null byte ignored in string initializer */
   1413 			warning(187);
   1414 		}
   1415 
   1416 		/*
   1417 		 * TODO: C99 6.7.8p14 allows a string literal to be enclosed
   1418 		 * in optional redundant braces, just like scalars.  Add tests
   1419 		 * for this.
   1420 		 */
   1421 	}
   1422 
   1423 	/* In every case the array is initialized completely. */
   1424 	level->bl_remaining = 0;
   1425 
   1426 	initialization_debug(in);
   1427 	debug_leave();
   1428 	return true;
   1429 }
   1430