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