Home | History | Annotate | Line # | Download | only in lint1
init.c revision 1.132
      1 /*	$NetBSD: init.c,v 1.132 2021/03/25 22:15:38 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.132 2021/03/25 22:15:38 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 /*
    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 designation_add_subscript(range_t range)
    519 {
    520 	initstack_element *istk;
    521 
    522 	debug_enter();
    523 	debug_step("subscript range is %zu ... %zu", range.lo, range.hi);
    524 	debug_initstack();
    525 
    526 	istk = initstk_lvalue;
    527 	if (istk->i_array_of_unknown_size) {
    528 		int auto_dim = (int)(range.hi + 1);
    529 		if (auto_dim > istk->i_type->t_dim) {
    530 			debug_step("setting the array size to %d", auto_dim);
    531 			istk->i_type->t_dim = auto_dim;
    532 		}
    533 	}
    534 
    535 	debug_leave();
    536 }
    537 
    538 /* TODO: add support for array subscripts, not only named members */
    539 static void
    540 designation_shift_level(void)
    541 {
    542 	/* TODO: remove direct access to 'init' */
    543 	lint_assert(init != NULL);
    544 	lint_assert(init->designation.head != NULL);
    545 	if (init->designation.head == init->designation.tail) {
    546 		free(init->designation.head);
    547 		init->designation.head = NULL;
    548 		init->designation.tail = NULL;
    549 	} else {
    550 		designator *head = init->designation.head;
    551 		init->designation.head = init->designation.head->next;
    552 		free(head);
    553 	}
    554 
    555 	debug_designation();
    556 }
    557 
    558 /*
    559  * Initialize the initialization stack by putting an entry for the object
    560  * which is to be initialized on it.
    561  *
    562  * TODO: merge into begin_initialization
    563  */
    564 void
    565 initstack_init(void)
    566 {
    567 	initstack_element *istk;
    568 
    569 	if (initerr)
    570 		return;
    571 
    572 	debug_enter();
    573 
    574 	/*
    575 	 * If the type which is to be initialized is an incomplete array,
    576 	 * it must be duplicated.
    577 	 */
    578 	if (initsym->s_type->t_tspec == ARRAY && is_incomplete(initsym->s_type))
    579 		initsym->s_type = duptyp(initsym->s_type);
    580 	/* TODO: does 'duptyp' create a memory leak? */
    581 
    582 	istk = initstk_lvalue = xcalloc(1, sizeof (initstack_element));
    583 	istk->i_subt = initsym->s_type;
    584 	istk->i_remaining = 1;
    585 
    586 	debug_initstack();
    587 	debug_leave();
    588 }
    589 
    590 /* TODO: document me */
    591 static void
    592 initstack_pop_item_named_member(void)
    593 {
    594 	initstack_element *istk = initstk_lvalue;
    595 	sym_t *m;
    596 
    597 	/*
    598 	 * TODO: fix wording of the debug message; this doesn't seem to be
    599 	 * related to initializing the named member.
    600 	 */
    601 	debug_step("initializing named member '%s'",
    602 	    current_designation().head->name);
    603 
    604 	if (istk->i_type->t_tspec != STRUCT &&
    605 	    istk->i_type->t_tspec != UNION) {
    606 		/* syntax error '%s' */
    607 		error(249, "named member must only be used with struct/union");
    608 		initerr = true;
    609 		return;
    610 	}
    611 
    612 	for (m = istk->i_type->t_str->sou_first_member;
    613 	     m != NULL; m = m->s_next) {
    614 
    615 		if (m->s_bitfield && m->s_name == unnamed)
    616 			continue;
    617 
    618 		if (strcmp(m->s_name, current_designation().head->name) == 0) {
    619 			debug_step("found matching member");
    620 			istk->i_subt = m->s_type;
    621 			/* XXX: why ++? */
    622 			istk->i_remaining++;
    623 			/* XXX: why is i_seen_named_member not set? */
    624 			designation_shift_level();
    625 			return;
    626 		}
    627 	}
    628 
    629 	/* undefined struct/union member: %s */
    630 	error(101, current_designation().head->name);
    631 
    632 	designation_shift_level();
    633 	istk->i_seen_named_member = true;
    634 }
    635 
    636 /* TODO: think of a better name than 'pop' */
    637 static void
    638 initstack_pop_item_unnamed(void)
    639 {
    640 	initstack_element *istk = initstk_lvalue;
    641 	sym_t *m;
    642 
    643 	/*
    644 	 * If the removed element was a structure member, we must go
    645 	 * to the next structure member.
    646 	 */
    647 	if (istk->i_remaining > 0 && istk->i_type->t_tspec == STRUCT &&
    648 	    !istk->i_seen_named_member) {
    649 		do {
    650 			m = istk->i_next_member =
    651 			    istk->i_next_member->s_next;
    652 			/* XXX: can this assertion be made to fail? */
    653 			lint_assert(m != NULL);
    654 			debug_step("pop %s", m->s_name);
    655 		} while (m->s_bitfield && m->s_name == unnamed);
    656 		/* XXX: duplicate code for skipping unnamed bit-fields */
    657 		istk->i_subt = m->s_type;
    658 	}
    659 }
    660 
    661 /* TODO: think of a better name than 'pop' */
    662 static void
    663 initstack_pop_item(void)
    664 {
    665 	initstack_element *istk;
    666 
    667 	debug_enter();
    668 
    669 	istk = initstk_lvalue;
    670 	debug_indent();
    671 	debug_printf("popping: ");
    672 	debug_initstack_element(istk);
    673 
    674 	initstk_lvalue = istk->i_enclosing;
    675 	free(istk);
    676 	istk = initstk_lvalue;
    677 	lint_assert(istk != NULL);
    678 
    679 	istk->i_remaining--;
    680 	lint_assert(istk->i_remaining >= 0);
    681 	debug_step("%d elements remaining", istk->i_remaining);
    682 
    683 	if (current_designation().head != NULL)
    684 		initstack_pop_item_named_member();
    685 	else
    686 		initstack_pop_item_unnamed();
    687 
    688 	debug_initstack();
    689 	debug_leave();
    690 }
    691 
    692 /*
    693  * Take all entries, including the first which requires a closing brace,
    694  * from the stack.
    695  */
    696 static void
    697 initstack_pop_brace(void)
    698 {
    699 	bool brace;
    700 
    701 	debug_enter();
    702 	debug_initstack();
    703 	do {
    704 		brace = initstk->i_brace;
    705 		/* TODO: improve wording of the debug message */
    706 		debug_step("loop brace=%d", brace);
    707 		initstack_pop_item();
    708 	} while (!brace);
    709 	debug_initstack();
    710 	debug_leave();
    711 }
    712 
    713 /*
    714  * Take all entries which cannot be used for further initializers from the
    715  * stack, but do this only if they do not require a closing brace.
    716  */
    717 /* TODO: think of a better name than 'pop' */
    718 static void
    719 initstack_pop_nobrace(void)
    720 {
    721 
    722 	debug_enter();
    723 	while (!initstk->i_brace && initstk->i_remaining == 0 &&
    724 	       !initstk->i_array_of_unknown_size)
    725 		initstack_pop_item();
    726 	debug_leave();
    727 }
    728 
    729 /* Extend an array of unknown size by one element */
    730 static void
    731 extend_if_array_of_unknown_size(void)
    732 {
    733 	initstack_element *istk = initstk_lvalue;
    734 
    735 	if (istk->i_remaining != 0)
    736 		return;
    737 
    738 	/*
    739 	 * The only place where an incomplete array may appear is at the
    740 	 * outermost aggregate level of the object to be initialized.
    741 	 */
    742 	lint_assert(istk->i_enclosing->i_enclosing == NULL);
    743 	lint_assert(istk->i_type->t_tspec == ARRAY);
    744 
    745 	debug_step("extending array of unknown size '%s'",
    746 	    type_name(istk->i_type));
    747 	istk->i_remaining = 1;
    748 	istk->i_type->t_dim++;
    749 	setcomplete(istk->i_type, true);
    750 
    751 	debug_step("extended type is '%s'", type_name(istk->i_type));
    752 }
    753 
    754 /* TODO: document me */
    755 /* TODO: think of a better name than 'push' */
    756 static void
    757 initstack_push_array(void)
    758 {
    759 	initstack_element *istk = initstk_lvalue;
    760 
    761 	if (istk->i_enclosing->i_seen_named_member) {
    762 		istk->i_brace = true;
    763 		debug_step("ARRAY%s%s",
    764 		    istk->i_brace ? ", needs closing brace" : "",
    765 		    istk->i_enclosing->i_seen_named_member
    766 			? ", seen named member" : "");
    767 	}
    768 
    769 	if (is_incomplete(istk->i_type) &&
    770 	    istk->i_enclosing->i_enclosing != NULL) {
    771 		/* initialization of an incomplete type */
    772 		error(175);
    773 		initerr = true;
    774 		return;
    775 	}
    776 
    777 	istk->i_subt = istk->i_type->t_subt;
    778 	istk->i_array_of_unknown_size = is_incomplete(istk->i_type);
    779 	istk->i_remaining = istk->i_type->t_dim;
    780 	debug_designation();
    781 	debug_step("type '%s' remaining %d",
    782 	    type_name(istk->i_type), istk->i_remaining);
    783 }
    784 
    785 /* TODO: document me */
    786 /* TODO: think of a better name than 'push' */
    787 static bool
    788 initstack_push_struct_or_union(void)
    789 {
    790 	/*
    791 	 * TODO: remove unnecessary 'const' for variables in functions that
    792 	 * fit on a single screen.  Keep it for larger functions.
    793 	 */
    794 	initstack_element *istk = initstk_lvalue;
    795 	int cnt;
    796 	sym_t *m;
    797 
    798 	if (is_incomplete(istk->i_type)) {
    799 		/* initialization of an incomplete type */
    800 		error(175);
    801 		initerr = true;
    802 		return false;
    803 	}
    804 
    805 	cnt = 0;
    806 	debug_designation();
    807 	debug_step("lookup for '%s'%s",
    808 	    type_name(istk->i_type),
    809 	    istk->i_seen_named_member ? ", seen named member" : "");
    810 
    811 	for (m = istk->i_type->t_str->sou_first_member;
    812 	     m != NULL; m = m->s_next) {
    813 		if (m->s_bitfield && m->s_name == unnamed)
    814 			continue;
    815 		/*
    816 		 * TODO: split into separate functions:
    817 		 *
    818 		 * look_up_array_next
    819 		 * look_up_array_designator
    820 		 * look_up_struct_next
    821 		 * look_up_struct_designator
    822 		 */
    823 		if (current_designation().head != NULL) {
    824 			/* XXX: this log entry looks unnecessarily verbose */
    825 			debug_step("have member '%s', want member '%s'",
    826 			    m->s_name, current_designation().head->name);
    827 			if (strcmp(m->s_name,
    828 			    current_designation().head->name) == 0) {
    829 				cnt++;
    830 				break;
    831 			} else
    832 				continue;
    833 		}
    834 		if (++cnt == 1) {
    835 			istk->i_next_member = m;
    836 			istk->i_subt = m->s_type;
    837 		}
    838 	}
    839 
    840 	if (current_designation().head != NULL) {
    841 		if (m == NULL) {
    842 			debug_step("pop struct");
    843 			return true;
    844 		}
    845 		istk->i_next_member = m;
    846 		istk->i_subt = m->s_type;
    847 		istk->i_seen_named_member = true;
    848 		debug_step("named member '%s'",
    849 		    current_designation().head->name);
    850 		designation_shift_level();
    851 		cnt = istk->i_type->t_tspec == STRUCT ? 2 : 1;
    852 	}
    853 	istk->i_brace = true;
    854 	debug_step("unnamed element with type '%s'%s",
    855 	    type_name(istk->i_type != NULL ? istk->i_type : istk->i_subt),
    856 	    istk->i_brace ? ", needs closing brace" : "");
    857 	if (cnt == 0) {
    858 		/* cannot init. struct/union with no named member */
    859 		error(179);
    860 		initerr = true;
    861 		return false;
    862 	}
    863 	istk->i_remaining = istk->i_type->t_tspec == STRUCT ? cnt : 1;
    864 	return false;
    865 }
    866 
    867 /* TODO: document me */
    868 /* TODO: think of a better name than 'push' */
    869 static void
    870 initstack_push(void)
    871 {
    872 	initstack_element *istk, *inxt;
    873 
    874 	debug_enter();
    875 
    876 	extend_if_array_of_unknown_size();
    877 
    878 	istk = initstk_lvalue;
    879 	lint_assert(istk->i_remaining > 0);
    880 	lint_assert(istk->i_type == NULL || !is_scalar(istk->i_type->t_tspec));
    881 
    882 	initstk_lvalue = xcalloc(1, sizeof (initstack_element));
    883 	initstk_lvalue->i_enclosing = istk;
    884 	initstk_lvalue->i_type = istk->i_subt;
    885 	lint_assert(initstk_lvalue->i_type->t_tspec != FUNC);
    886 
    887 again:
    888 	istk = initstk_lvalue;
    889 
    890 	debug_step("expecting type '%s'", type_name(istk->i_type));
    891 	lint_assert(istk->i_type != NULL);
    892 	switch (istk->i_type->t_tspec) {
    893 	case ARRAY:
    894 		if (current_designation().head != NULL) {
    895 			debug_step("pop array, named member '%s'%s",
    896 			    current_designation().head->name,
    897 			    istk->i_brace ? ", needs closing brace" : "");
    898 			goto pop;
    899 		}
    900 
    901 		initstack_push_array();
    902 		break;
    903 
    904 	case UNION:
    905 		if (tflag)
    906 			/* initialization of union is illegal in trad. C */
    907 			warning(238);
    908 		/* FALLTHROUGH */
    909 	case STRUCT:
    910 		if (initstack_push_struct_or_union())
    911 			goto pop;
    912 		break;
    913 	default:
    914 		if (current_designation().head != NULL) {
    915 			debug_step("pop scalar");
    916 	pop:
    917 			/* TODO: extract this into end_initializer_level */
    918 			inxt = initstk->i_enclosing;
    919 			free(istk);
    920 			initstk_lvalue = inxt;
    921 			goto again;
    922 		}
    923 		/* The initialization stack now expects a single scalar. */
    924 		istk->i_remaining = 1;
    925 		break;
    926 	}
    927 
    928 	debug_initstack();
    929 	debug_leave();
    930 }
    931 
    932 static void
    933 check_too_many_initializers(void)
    934 {
    935 
    936 	const initstack_element *istk = initstk;
    937 	if (istk->i_remaining > 0)
    938 		return;
    939 	/*
    940 	 * FIXME: even with named members, there can be too many initializers
    941 	 */
    942 	if (istk->i_array_of_unknown_size || istk->i_seen_named_member)
    943 		return;
    944 
    945 	tspec_t t = istk->i_type->t_tspec;
    946 	if (t == ARRAY) {
    947 		/* too many array initializers, expected %d */
    948 		error(173, istk->i_type->t_dim);
    949 	} else if (t == STRUCT || t == UNION) {
    950 		/* too many struct/union initializers */
    951 		error(172);
    952 	} else {
    953 		/* too many initializers */
    954 		error(174);
    955 	}
    956 	initerr = true;
    957 }
    958 
    959 /*
    960  * Process a '{' in an initializer by starting the initialization of the
    961  * nested data structure, with i_type being the i_subt of the outer
    962  * initialization level.
    963  */
    964 static void
    965 initstack_next_brace(void)
    966 {
    967 
    968 	debug_enter();
    969 	debug_initstack();
    970 
    971 	if (initstk->i_type != NULL && is_scalar(initstk->i_type->t_tspec)) {
    972 		/* invalid initializer type %s */
    973 		error(176, type_name(initstk->i_type));
    974 		initerr = true;
    975 	}
    976 	if (!initerr)
    977 		check_too_many_initializers();
    978 	if (!initerr)
    979 		initstack_push();
    980 	if (!initerr) {
    981 		initstk_lvalue->i_brace = true;
    982 		debug_designation();
    983 		debug_step("expecting type '%s'",
    984 		    type_name(initstk->i_type != NULL ? initstk->i_type
    985 			: initstk->i_subt));
    986 	}
    987 
    988 	debug_initstack();
    989 	debug_leave();
    990 }
    991 
    992 /* TODO: document me, or think of a better name */
    993 static void
    994 initstack_next_nobrace(tnode_t *tn)
    995 {
    996 	debug_enter();
    997 
    998 	if (initstk->i_type == NULL && !is_scalar(initstk->i_subt->t_tspec)) {
    999 		/* {}-enclosed initializer required */
   1000 		error(181);
   1001 		/* XXX: maybe set initerr here */
   1002 	}
   1003 
   1004 	if (!initerr)
   1005 		check_too_many_initializers();
   1006 
   1007 	while (!initerr) {
   1008 		initstack_element *istk = initstk_lvalue;
   1009 
   1010 		if (tn->tn_type->t_tspec == STRUCT &&
   1011 		    istk->i_type == tn->tn_type &&
   1012 		    istk->i_enclosing != NULL &&
   1013 		    istk->i_enclosing->i_enclosing != NULL) {
   1014 			istk->i_brace = false;
   1015 			istk->i_remaining = 1; /* the struct itself */
   1016 			break;
   1017 		}
   1018 
   1019 		if ((istk->i_type != NULL && is_scalar(istk->i_type->t_tspec)))
   1020 			break;
   1021 		initstack_push();
   1022 	}
   1023 
   1024 	debug_initstack();
   1025 	debug_leave();
   1026 }
   1027 
   1028 /* TODO: document me */
   1029 void
   1030 init_lbrace(void)
   1031 {
   1032 	if (initerr)
   1033 		return;
   1034 
   1035 	debug_enter();
   1036 	debug_initstack();
   1037 
   1038 	if ((initsym->s_scl == AUTO || initsym->s_scl == REG) &&
   1039 	    initstk->i_enclosing == NULL) {
   1040 		if (tflag && !is_scalar(initstk->i_subt->t_tspec))
   1041 			/* no automatic aggregate initialization in trad. C */
   1042 			warning(188);
   1043 	}
   1044 
   1045 	/*
   1046 	 * Remove all entries which cannot be used for further initializers
   1047 	 * and do not expect a closing brace.
   1048 	 */
   1049 	initstack_pop_nobrace();
   1050 
   1051 	initstack_next_brace();
   1052 
   1053 	debug_initstack();
   1054 	debug_leave();
   1055 }
   1056 
   1057 /*
   1058  * Process a '}' in an initializer by finishing the current level of the
   1059  * initialization stack.
   1060  */
   1061 void
   1062 init_rbrace(void)
   1063 {
   1064 	if (initerr)
   1065 		return;
   1066 
   1067 	debug_enter();
   1068 	initstack_pop_brace();
   1069 	debug_leave();
   1070 }
   1071 
   1072 /* In traditional C, bit-fields can be initialized only by integer constants. */
   1073 static void
   1074 check_bit_field_init(const tnode_t *ln, tspec_t lt, tspec_t rt)
   1075 {
   1076 	if (tflag &&
   1077 	    is_integer(lt) &&
   1078 	    ln->tn_type->t_bitfield &&
   1079 	    !is_integer(rt)) {
   1080 		/* bit-field initialization is illegal in traditional C */
   1081 		warning(186);
   1082 	}
   1083 }
   1084 
   1085 static void
   1086 check_non_constant_initializer(const tnode_t *tn, scl_t sclass)
   1087 {
   1088 	/* TODO: rename CON to CONSTANT to avoid ambiguity with CONVERT */
   1089 	if (tn == NULL || tn->tn_op == CON)
   1090 		return;
   1091 
   1092 	sym_t *sym;
   1093 	ptrdiff_t offs;
   1094 	if (constant_addr(tn, &sym, &offs))
   1095 		return;
   1096 
   1097 	if (sclass == AUTO || sclass == REG) {
   1098 		/* non-constant initializer */
   1099 		c99ism(177);
   1100 	} else {
   1101 		/* non-constant initializer */
   1102 		error(177);
   1103 	}
   1104 }
   1105 
   1106 /*
   1107  * Initialize a non-array object with automatic storage duration and only a
   1108  * single initializer expression without braces by delegating to ASSIGN.
   1109  */
   1110 static bool
   1111 init_using_assign(tnode_t *rn)
   1112 {
   1113 	tnode_t *ln, *tn;
   1114 
   1115 	if (initsym->s_type->t_tspec == ARRAY)
   1116 		return false;
   1117 	if (initstk->i_enclosing != NULL)
   1118 		return false;
   1119 
   1120 	debug_step("handing over to ASSIGN");
   1121 
   1122 	ln = new_name_node(initsym, 0);
   1123 	ln->tn_type = tduptyp(ln->tn_type);
   1124 	ln->tn_type->t_const = false;
   1125 
   1126 	tn = build(ASSIGN, ln, rn);
   1127 	expr(tn, false, false, false, false);
   1128 
   1129 	/* XXX: why not clean up the initstack here already? */
   1130 	return true;
   1131 }
   1132 
   1133 static void
   1134 check_init_expr(tnode_t *tn, scl_t sclass)
   1135 {
   1136 	tnode_t *ln;
   1137 	tspec_t lt, rt;
   1138 	struct mbl *tmem;
   1139 
   1140 	/* Create a temporary node for the left side. */
   1141 	ln = tgetblk(sizeof (tnode_t));
   1142 	ln->tn_op = NAME;
   1143 	ln->tn_type = tduptyp(initstk->i_type);
   1144 	ln->tn_type->t_const = false;
   1145 	ln->tn_lvalue = true;
   1146 	ln->tn_sym = initsym;		/* better than nothing */
   1147 
   1148 	tn = cconv(tn);
   1149 
   1150 	lt = ln->tn_type->t_tspec;
   1151 	rt = tn->tn_type->t_tspec;
   1152 
   1153 	debug_step("typeok '%s', '%s'",
   1154 	    type_name(ln->tn_type), type_name(tn->tn_type));
   1155 	if (!typeok(INIT, 0, ln, tn))
   1156 		return;
   1157 
   1158 	/*
   1159 	 * Preserve the tree memory. This is necessary because otherwise
   1160 	 * expr() would free it.
   1161 	 */
   1162 	tmem = tsave();
   1163 	expr(tn, true, false, true, false);
   1164 	trestor(tmem);
   1165 
   1166 	check_bit_field_init(ln, lt, rt);
   1167 
   1168 	/*
   1169 	 * XXX: Is it correct to do this conversion _after_ the typeok above?
   1170 	 */
   1171 	if (lt != rt || (initstk->i_type->t_bitfield && tn->tn_op == CON))
   1172 		tn = convert(INIT, 0, initstk->i_type, tn);
   1173 
   1174 	check_non_constant_initializer(tn, sclass);
   1175 }
   1176 
   1177 void
   1178 init_using_expr(tnode_t *tn)
   1179 {
   1180 	scl_t	sclass;
   1181 
   1182 	debug_enter();
   1183 	debug_initstack();
   1184 	debug_designation();
   1185 	debug_step("expr:");
   1186 	debug_node(tn, debug_ind + 1);
   1187 
   1188 	if (initerr || tn == NULL)
   1189 		goto done;
   1190 
   1191 	sclass = initsym->s_scl;
   1192 	if ((sclass == AUTO || sclass == REG) && init_using_assign(tn))
   1193 		goto done;
   1194 
   1195 	initstack_pop_nobrace();
   1196 
   1197 	if (init_array_using_string(tn)) {
   1198 		debug_step("after initializing the string:");
   1199 		/* XXX: why not clean up the initstack here already? */
   1200 		goto done_initstack;
   1201 	}
   1202 
   1203 	initstack_next_nobrace(tn);
   1204 	if (initerr || tn == NULL)
   1205 		goto done_initstack;
   1206 
   1207 	initstk_lvalue->i_remaining--;
   1208 	debug_step("%d elements remaining", initstk->i_remaining);
   1209 
   1210 	check_init_expr(tn, sclass);
   1211 
   1212 done_initstack:
   1213 	debug_initstack();
   1214 
   1215 done:
   1216 	while (current_designation().head != NULL)
   1217 		designation_shift_level();
   1218 
   1219 	debug_leave();
   1220 }
   1221 
   1222 
   1223 /* Initialize a character array or wchar_t array with a string literal. */
   1224 static bool
   1225 init_array_using_string(tnode_t *tn)
   1226 {
   1227 	tspec_t	t;
   1228 	initstack_element *istk;
   1229 	int	len;
   1230 	strg_t	*strg;
   1231 
   1232 	if (tn->tn_op != STRING)
   1233 		return false;
   1234 
   1235 	debug_enter();
   1236 	debug_initstack();
   1237 
   1238 	istk = initstk_lvalue;
   1239 	strg = tn->tn_string;
   1240 
   1241 	/*
   1242 	 * Check if we have an array type which can be initialized by
   1243 	 * the string.
   1244 	 */
   1245 	if (istk->i_subt != NULL && istk->i_subt->t_tspec == ARRAY) {
   1246 		debug_step("subt array");
   1247 		t = istk->i_subt->t_subt->t_tspec;
   1248 		if (!((strg->st_tspec == CHAR &&
   1249 		       (t == CHAR || t == UCHAR || t == SCHAR)) ||
   1250 		      (strg->st_tspec == WCHAR && t == WCHAR))) {
   1251 			debug_leave();
   1252 			return false;
   1253 		}
   1254 		/* XXX: duplicate code, see below */
   1255 
   1256 		/* Put the array at top of stack */
   1257 		initstack_push();
   1258 		istk = initstk_lvalue;
   1259 
   1260 
   1261 		/* TODO: what if both i_type and i_subt are ARRAY? */
   1262 
   1263 	} else if (istk->i_type != NULL && istk->i_type->t_tspec == ARRAY) {
   1264 		debug_step("type array");
   1265 		t = istk->i_type->t_subt->t_tspec;
   1266 		if (!((strg->st_tspec == CHAR &&
   1267 		       (t == CHAR || t == UCHAR || t == SCHAR)) ||
   1268 		      (strg->st_tspec == WCHAR && t == WCHAR))) {
   1269 			debug_leave();
   1270 			return false;
   1271 		}
   1272 		/* XXX: duplicate code, see above */
   1273 
   1274 		/*
   1275 		 * TODO: is this really not needed in the branch above this
   1276 		 * one?
   1277 		 */
   1278 		/*
   1279 		 * If the array is already partly initialized, we are
   1280 		 * wrong here.
   1281 		 */
   1282 		if (istk->i_remaining != istk->i_type->t_dim) {
   1283 			debug_leave();
   1284 			return false;
   1285 		}
   1286 	} else {
   1287 		debug_leave();
   1288 		return false;
   1289 	}
   1290 
   1291 	/* Get length without trailing NUL character. */
   1292 	len = strg->st_len;
   1293 
   1294 	if (istk->i_array_of_unknown_size) {
   1295 		/*
   1296 		 * FIXME: C99 6.7.8p22 explicitly says that only "at the end
   1297 		 * of its initializer list, the array no longer has incomplete
   1298 		 * type".
   1299 		 */
   1300 		istk->i_array_of_unknown_size = false;
   1301 		istk->i_type->t_dim = len + 1;
   1302 		setcomplete(istk->i_type, true);
   1303 	} else {
   1304 		/*
   1305 		 * TODO: check for buffer overflow in the object to be
   1306 		 * initialized
   1307 		 */
   1308 		/* XXX: double-check for off-by-one error */
   1309 		if (istk->i_type->t_dim < len) {
   1310 			/* non-null byte ignored in string initializer */
   1311 			warning(187);
   1312 		}
   1313 
   1314 		/*
   1315 		 * TODO: C99 6.7.8p14 allows a string literal to be enclosed
   1316 		 * in optional redundant braces, just like scalars.  Add tests
   1317 		 * for this.
   1318 		 */
   1319 	}
   1320 
   1321 	/* In every case the array is initialized completely. */
   1322 	istk->i_remaining = 0;
   1323 
   1324 	debug_initstack();
   1325 	debug_leave();
   1326 	return true;
   1327 }
   1328