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