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