Home | History | Annotate | Line # | Download | only in lint1
init.c revision 1.99
      1 /*	$NetBSD: init.c,v 1.99 2021/03/18 23:45:20 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.99 2021/03/18 23:45:20 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 = 3, .x = 4 };
     63  *
     64  * The initializer that follows the '=' may be surrounded by an extra pair of
     65  * braces, like in the example 'number_with_braces'.  For multi-dimensional
     66  * arrays, the inner braces may be omitted like in array_flat or spelled out
     67  * like in array_nested.
     68  *
     69  * For the initializer, the grammar parser calls these functions:
     70  *
     71  *	init_lbrace	for each '{'
     72  *	init_using_expr	for each value
     73  *	init_rbrace	for each '}'
     74  *
     75  * The state of the current initialization is stored in initstk, a stack of
     76  * initstack_element, one element per type aggregate level.
     77  *
     78  * Most of the time, the topmost level of initstk contains a scalar type, and
     79  * its remaining count toggles between 1 and 0.
     80  *
     81  * See also:
     82  *	C99 6.7.8 "Initialization"
     83  *	d_c99_init.c for more examples
     84  */
     85 
     86 
     87 /*
     88  * Type of stack which is used for initialization of aggregate types.
     89  *
     90  * XXX: Since C99, a stack is an inappropriate data structure for modelling
     91  * an initialization, since the designators don't have to be listed in a
     92  * particular order and can designate parts of sub-objects.  The member names
     93  * of non-leaf structs may thus appear repeatedly, as demonstrated in
     94  * d_init_pop_member.c.
     95  *
     96  * XXX: During initialization, there may be members of the top-level struct
     97  * that are partially initialized.  The simple i_remaining cannot model this
     98  * appropriately.
     99  *
    100  * See C99 6.7.8, which spans 6 pages full of tricky details and carefully
    101  * selected examples.
    102  */
    103 typedef	struct initstack_element {
    104 
    105 	/*
    106 	 * The type to be initialized at this level.
    107 	 */
    108 	type_t	*i_type;
    109 	/*
    110 	 * The type that is initialized inside a further level of
    111 	 * braces.  It is completely independent from i_type->t_subt.
    112 	 *
    113 	 * For example, in 'int var = { init }', initially there is an
    114 	 * initstack_element with i_subt == int.  When the '{' is processed,
    115 	 * an element with i_type == int is pushed to the stack.  When the
    116 	 * corresponding '}' is processed, the inner element is popped again.
    117 	 *
    118 	 * During initialization, only the top 2 elements of the stack are
    119 	 * looked at.
    120 	 */
    121 	type_t	*i_subt;
    122 
    123 	/*
    124 	 * This level of the initializer requires a '}' to be completed.
    125 	 *
    126 	 * Multidimensional arrays do not need a closing brace to complete
    127 	 * an inner array; for example, { 1, 2, 3, 4 } is a valid initializer
    128 	 * for int arr[2][2].
    129 	 *
    130 	 * TODO: Do structs containing structs need a closing brace?
    131 	 * TODO: Do arrays of structs need a closing brace after each struct?
    132 	 */
    133 	bool i_brace: 1;
    134 
    135 	/* Whether i_type is an array of unknown size. */
    136 	bool i_array_of_unknown_size: 1;
    137 	bool i_seen_named_member: 1;
    138 
    139 	/*
    140 	 * For structs, the next member to be initialized by an initializer
    141 	 * without an optional designator.
    142 	 */
    143 	sym_t *i_current_object;
    144 
    145 	/*
    146 	 * The number of remaining elements.
    147 	 *
    148 	 * For an array of unknown size, this is always 0 and thus irrelevant.
    149 	 *
    150 	 * XXX: for scalars?
    151 	 * XXX: for structs?
    152 	 * XXX: for unions?
    153 	 * XXX: for arrays?
    154 	 */
    155 	int i_remaining;
    156 
    157 	/*
    158 	 * The initialization state of the enclosing data structure
    159 	 * (struct, union, array).
    160 	 */
    161 	struct initstack_element *i_enclosing;
    162 } initstack_element;
    163 
    164 /*
    165  * The names for a nested C99 initialization designator, in a circular list.
    166  *
    167  * Example:
    168  *	struct stat st = {
    169  *		.st_size = 123,
    170  *		.st_mtim.tv_sec = 45,
    171  *		.st_mtim.tv_nsec
    172  *	};
    173  *
    174  *	During initialization, this list first contains ["st_size"], then
    175  *	["st_mtim", "tv_sec"], then ["st_mtim", "tv_nsec"].
    176  */
    177 typedef struct namlist {
    178 	const char *n_name;
    179 	struct namlist *n_prev;
    180 	struct namlist *n_next;
    181 } namlist_t;
    182 
    183 
    184 /*
    185  * initerr is set as soon as a fatal error occurred in an initialization.
    186  * The effect is that the rest of the initialization is ignored (parsed
    187  * by yacc, expression trees built, but no initialization takes place).
    188  */
    189 bool	initerr;
    190 
    191 /* Pointer to the symbol which is to be initialized. */
    192 sym_t	*initsym;
    193 
    194 /* Points to the top element of the initialization stack. */
    195 initstack_element *initstk;
    196 
    197 /* Points to a c9x named member; */
    198 namlist_t	*namedmem = NULL;
    199 
    200 
    201 static	bool	init_array_using_string(tnode_t *);
    202 
    203 #ifndef DEBUG
    204 
    205 #define debug_printf(fmt, ...)	do { } while (false)
    206 #define debug_indent()		do { } while (false)
    207 #define debug_enter(a)		do { } while (false)
    208 #define debug_step(fmt, ...)	do { } while (false)
    209 #define debug_leave(a)		do { } while (false)
    210 #define debug_named_member()	do { } while (false)
    211 #define debug_initstack_element(elem) do { } while (false)
    212 #define debug_initstack()	do { } while (false)
    213 
    214 #else
    215 
    216 static int debug_ind = 0;
    217 
    218 static void __printflike(1, 2)
    219 debug_printf(const char *fmt, ...)
    220 {
    221 	va_list va;
    222 
    223 	va_start(va, fmt);
    224 	vfprintf(stdout, fmt, va);
    225 	va_end(va);
    226 }
    227 
    228 static void
    229 debug_indent(void)
    230 {
    231 	debug_printf("%*s", 2 * debug_ind, "");
    232 }
    233 
    234 static void
    235 debug_enter(const char *func)
    236 {
    237 	printf("%*s+ %s\n", 2 * debug_ind++, "", func);
    238 }
    239 
    240 static void __printflike(1, 2)
    241 debug_step(const char *fmt, ...)
    242 {
    243 	va_list va;
    244 
    245 	printf("%*s", 2 * debug_ind, "");
    246 	va_start(va, fmt);
    247 	vfprintf(stdout, fmt, va);
    248 	va_end(va);
    249 	printf("\n");
    250 }
    251 
    252 static void
    253 debug_leave(const char *func)
    254 {
    255 	printf("%*s- %s\n", 2 * --debug_ind, "", func);
    256 }
    257 
    258 static void
    259 debug_named_member(void)
    260 {
    261 	namlist_t *name;
    262 
    263 	if (namedmem == NULL)
    264 		return;
    265 	name = namedmem;
    266 	debug_indent();
    267 	debug_printf("named member:");
    268 	do {
    269 		debug_printf(" %s", name->n_name);
    270 		name = name->n_next;
    271 	} while (name != namedmem);
    272 	debug_printf("\n");
    273 }
    274 
    275 static void
    276 debug_initstack_element(const initstack_element *elem)
    277 {
    278 	if (elem->i_type != NULL)
    279 		debug_step("  i_type           = %s", type_name(elem->i_type));
    280 	if (elem->i_subt != NULL)
    281 		debug_step("  i_subt           = %s", type_name(elem->i_subt));
    282 
    283 	if (elem->i_brace)
    284 		debug_step("  i_brace");
    285 	if (elem->i_array_of_unknown_size)
    286 		debug_step("  i_array_of_unknown_size");
    287 	if (elem->i_seen_named_member)
    288 		debug_step("  i_seen_named_member");
    289 
    290 	const type_t *eff_type = elem->i_type != NULL
    291 	    ? elem->i_type : elem->i_subt;
    292 	if (eff_type->t_tspec == STRUCT && elem->i_current_object != NULL)
    293 		debug_step("  i_current_object = %s",
    294 		    elem->i_current_object->s_name);
    295 
    296 	debug_step("  i_remaining      = %d", elem->i_remaining);
    297 }
    298 
    299 static void
    300 debug_initstack(void)
    301 {
    302 	if (initstk == NULL) {
    303 		debug_step("initstk is empty");
    304 		return;
    305 	}
    306 
    307 	size_t i = 0;
    308 	for (const initstack_element *elem = initstk;
    309 	     elem != NULL; elem = elem->i_enclosing) {
    310 		debug_step("initstk[%zu]:", i);
    311 		debug_initstack_element(elem);
    312 		i++;
    313 	}
    314 }
    315 
    316 #define debug_enter() debug_enter(__func__)
    317 #define debug_leave() debug_leave(__func__)
    318 
    319 #endif
    320 
    321 void
    322 push_member(sbuf_t *sb)
    323 {
    324 	namlist_t *nam = xcalloc(1, sizeof (namlist_t));
    325 	nam->n_name = sb->sb_name;
    326 
    327 	debug_step("%s: '%s' %p", __func__, nam->n_name, nam);
    328 
    329 	if (namedmem == NULL) {
    330 		/*
    331 		 * XXX: Why is this a circular list?
    332 		 * XXX: Why is this a doubly-linked list?
    333 		 * A simple stack should suffice.
    334 		 */
    335 		nam->n_prev = nam->n_next = nam;
    336 		namedmem = nam;
    337 	} else {
    338 		namedmem->n_prev->n_next = nam;
    339 		nam->n_prev = namedmem->n_prev;
    340 		nam->n_next = namedmem;
    341 		namedmem->n_prev = nam;
    342 	}
    343 }
    344 
    345 /*
    346  * A struct member that has array type is initialized using a designator.
    347  *
    348  * C99 example: struct { int member[4]; } var = { [2] = 12345 };
    349  *
    350  * GNU example: struct { int member[4]; } var = { [1 ... 3] = 12345 };
    351  */
    352 void
    353 designator_push_subscript(range_t range)
    354 {
    355 	debug_enter();
    356 	debug_step("subscript range is %zu ... %zu", range.lo, range.hi);
    357 	debug_initstack();
    358 	debug_leave();
    359 }
    360 
    361 static void
    362 pop_member(void)
    363 {
    364 	debug_step("%s: %s %p", __func__, namedmem->n_name, namedmem);
    365 	if (namedmem->n_next == namedmem) {
    366 		free(namedmem);
    367 		namedmem = NULL;
    368 	} else {
    369 		namlist_t *nam = namedmem;
    370 		namedmem = namedmem->n_next;
    371 		nam->n_prev->n_next = nam->n_next;
    372 		nam->n_next->n_prev = nam->n_prev;
    373 		free(nam);
    374 	}
    375 }
    376 
    377 /*
    378  * Initialize the initialization stack by putting an entry for the object
    379  * which is to be initialized on it.
    380  */
    381 void
    382 initstack_init(void)
    383 {
    384 	initstack_element *istk;
    385 
    386 	if (initerr)
    387 		return;
    388 
    389 	/* free memory used in last initialization */
    390 	while ((istk = initstk) != NULL) {
    391 		initstk = istk->i_enclosing;
    392 		free(istk);
    393 	}
    394 
    395 	debug_enter();
    396 
    397 	/*
    398 	 * If the type which is to be initialized is an incomplete array,
    399 	 * it must be duplicated.
    400 	 */
    401 	if (initsym->s_type->t_tspec == ARRAY && is_incomplete(initsym->s_type))
    402 		initsym->s_type = duptyp(initsym->s_type);
    403 
    404 	istk = initstk = xcalloc(1, sizeof (initstack_element));
    405 	istk->i_subt = initsym->s_type;
    406 	istk->i_remaining = 1;
    407 
    408 	debug_initstack();
    409 	debug_leave();
    410 }
    411 
    412 static void
    413 initstack_pop_item(void)
    414 {
    415 	initstack_element *istk;
    416 	sym_t	*m;
    417 
    418 	debug_enter();
    419 
    420 	istk = initstk;
    421 	debug_step("popping:");
    422 	debug_initstack_element(istk);
    423 
    424 	initstk = istk->i_enclosing;
    425 	free(istk);
    426 	istk = initstk;
    427 	lint_assert(istk != NULL);
    428 
    429 	istk->i_remaining--;
    430 	lint_assert(istk->i_remaining >= 0);
    431 	debug_step("%d elements remaining", istk->i_remaining);
    432 
    433 	if (namedmem != NULL) {
    434 		debug_step("initializing named member '%s'", namedmem->n_name);
    435 
    436 		lint_assert(istk->i_type->t_tspec == STRUCT ||
    437 		    istk->i_type->t_tspec == UNION);
    438 		for (m = istk->i_type->t_str->sou_first_member;
    439 		     m != NULL; m = m->s_next) {
    440 
    441 			if (m->s_bitfield && m->s_name == unnamed)
    442 				continue;
    443 
    444 			if (strcmp(m->s_name, namedmem->n_name) == 0) {
    445 				debug_step("found matching member");
    446 				istk->i_subt = m->s_type;
    447 				/* XXX: why ++? */
    448 				istk->i_remaining++;
    449 				/* XXX: why is i_seen_named_member not set? */
    450 				pop_member();
    451 				debug_initstack();
    452 				debug_leave();
    453 				return;
    454 			}
    455 		}
    456 
    457 		/* undefined struct/union member: %s */
    458 		error(101, namedmem->n_name);
    459 
    460 		pop_member();
    461 		istk->i_seen_named_member = true;
    462 		debug_initstack();
    463 		debug_leave();
    464 		return;
    465 	}
    466 
    467 	/*
    468 	 * If the removed element was a structure member, we must go
    469 	 * to the next structure member.
    470 	 */
    471 	if (istk->i_remaining > 0 && istk->i_type->t_tspec == STRUCT &&
    472 	    !istk->i_seen_named_member) {
    473 		do {
    474 			m = istk->i_current_object =
    475 			    istk->i_current_object->s_next;
    476 			/* XXX: can this assertion be made to fail? */
    477 			lint_assert(m != NULL);
    478 			debug_step("pop %s", m->s_name);
    479 		} while (m->s_bitfield && m->s_name == unnamed);
    480 		/* XXX: duplicate code for skipping unnamed bit-fields */
    481 		istk->i_subt = m->s_type;
    482 	}
    483 	debug_initstack();
    484 	debug_leave();
    485 }
    486 
    487 /*
    488  * Take all entries, including the first which requires a closing brace,
    489  * from the stack.
    490  */
    491 static void
    492 initstack_pop_brace(void)
    493 {
    494 	bool brace;
    495 
    496 	debug_enter();
    497 	debug_initstack();
    498 	do {
    499 		brace = initstk->i_brace;
    500 		debug_step("loop brace=%d", brace);
    501 		initstack_pop_item();
    502 	} while (!brace);
    503 	debug_initstack();
    504 	debug_leave();
    505 }
    506 
    507 /*
    508  * Take all entries which cannot be used for further initializers from the
    509  * stack, but do this only if they do not require a closing brace.
    510  */
    511 static void
    512 initstack_pop_nobrace(void)
    513 {
    514 
    515 	debug_enter();
    516 	while (!initstk->i_brace && initstk->i_remaining == 0 &&
    517 	       !initstk->i_array_of_unknown_size)
    518 		initstack_pop_item();
    519 	debug_leave();
    520 }
    521 
    522 /* Extend an array of unknown size by one element */
    523 static void
    524 extend_if_array_of_unknown_size(void)
    525 {
    526 	initstack_element *istk = initstk;
    527 
    528 	if (istk->i_remaining != 0)
    529 		return;
    530 
    531 	/*
    532 	 * The only place where an incomplete array may appear is at the
    533 	 * outermost aggregate level of the object to be initialized.
    534 	 */
    535 	lint_assert(istk->i_enclosing->i_enclosing == NULL);
    536 	lint_assert(istk->i_type->t_tspec == ARRAY);
    537 
    538 	debug_step("extending array of unknown size '%s'",
    539 	    type_name(istk->i_type));
    540 	istk->i_remaining = 1;
    541 	istk->i_type->t_dim++;
    542 	setcomplete(istk->i_type, true);
    543 
    544 	debug_step("extended type is '%s'", type_name(istk->i_type));
    545 }
    546 
    547 static void
    548 initstack_push_array(void)
    549 {
    550 	initstack_element *const istk = initstk;
    551 
    552 	if (istk->i_enclosing->i_seen_named_member) {
    553 		istk->i_brace = true;
    554 		debug_step("ARRAY brace=%d, namedmem=%d",
    555 		    istk->i_brace, istk->i_enclosing->i_seen_named_member);
    556 	}
    557 
    558 	if (is_incomplete(istk->i_type) &&
    559 	    istk->i_enclosing->i_enclosing != NULL) {
    560 		/* initialization of an incomplete type */
    561 		error(175);
    562 		initerr = true;
    563 		return;
    564 	}
    565 
    566 	istk->i_subt = istk->i_type->t_subt;
    567 	istk->i_array_of_unknown_size = is_incomplete(istk->i_type);
    568 	istk->i_remaining = istk->i_type->t_dim;
    569 	debug_named_member();
    570 	debug_step("type '%s' remaining %d",
    571 	    type_name(istk->i_type), istk->i_remaining);
    572 }
    573 
    574 static bool
    575 initstack_push_struct_or_union(void)
    576 {
    577 	initstack_element *const istk = initstk;
    578 	int cnt;
    579 	sym_t *m;
    580 
    581 	if (is_incomplete(istk->i_type)) {
    582 		/* initialization of an incomplete type */
    583 		error(175);
    584 		initerr = true;
    585 		return false;
    586 	}
    587 	cnt = 0;
    588 	debug_named_member();
    589 	debug_step("lookup for '%s'%s",
    590 	    type_name(istk->i_type),
    591 	    istk->i_seen_named_member ? ", seen named member" : "");
    592 	for (m = istk->i_type->t_str->sou_first_member;
    593 	     m != NULL; m = m->s_next) {
    594 		if (m->s_bitfield && m->s_name == unnamed)
    595 			continue;
    596 		if (namedmem != NULL) {
    597 			debug_step("named lhs.member=%s, rhs.member=%s",
    598 			    m->s_name, namedmem->n_name);
    599 			if (strcmp(m->s_name, namedmem->n_name) == 0) {
    600 				cnt++;
    601 				break;
    602 			} else
    603 				continue;
    604 		}
    605 		if (++cnt == 1) {
    606 			istk->i_current_object = m;
    607 			istk->i_subt = m->s_type;
    608 		}
    609 	}
    610 	if (namedmem != NULL) {
    611 		if (m == NULL) {
    612 			debug_step("pop struct");
    613 			return true;
    614 		}
    615 		istk->i_current_object = m;
    616 		istk->i_subt = m->s_type;
    617 		istk->i_seen_named_member = true;
    618 		debug_step("named member '%s'", namedmem->n_name);
    619 		pop_member();
    620 		cnt = istk->i_type->t_tspec == STRUCT ? 2 : 1;
    621 	}
    622 	istk->i_brace = true;
    623 	debug_step("unnamed element with type '%s'%s",
    624 	    type_name(istk->i_type != NULL ? istk->i_type : istk->i_subt),
    625 	    istk->i_brace ? ", needs closing brace" : "");
    626 	if (cnt == 0) {
    627 		/* cannot init. struct/union with no named member */
    628 		error(179);
    629 		initerr = true;
    630 		return false;
    631 	}
    632 	istk->i_remaining = istk->i_type->t_tspec == STRUCT ? cnt : 1;
    633 	return false;
    634 }
    635 
    636 static void
    637 initstack_push(void)
    638 {
    639 	initstack_element *istk, *inxt;
    640 
    641 	debug_enter();
    642 
    643 	extend_if_array_of_unknown_size();
    644 
    645 	istk = initstk;
    646 	lint_assert(istk->i_remaining > 0);
    647 	lint_assert(istk->i_type == NULL || !is_scalar(istk->i_type->t_tspec));
    648 
    649 	initstk = xcalloc(1, sizeof (initstack_element));
    650 	initstk->i_enclosing = istk;
    651 	initstk->i_type = istk->i_subt;
    652 	lint_assert(initstk->i_type->t_tspec != FUNC);
    653 
    654 again:
    655 	istk = initstk;
    656 
    657 	debug_step("expecting type '%s'", type_name(istk->i_type));
    658 	switch (istk->i_type->t_tspec) {
    659 	case ARRAY:
    660 		if (namedmem != NULL) {
    661 			debug_step("ARRAY %s brace=%d",
    662 			    namedmem->n_name, istk->i_brace);
    663 			goto pop;
    664 		}
    665 
    666 		initstack_push_array();
    667 		break;
    668 
    669 	case UNION:
    670 		if (tflag)
    671 			/* initialization of union is illegal in trad. C */
    672 			warning(238);
    673 		/* FALLTHROUGH */
    674 	case STRUCT:
    675 		if (initstack_push_struct_or_union())
    676 			goto pop;
    677 		break;
    678 	default:
    679 		if (namedmem != NULL) {
    680 			debug_step("pop");
    681 	pop:
    682 			inxt = initstk->i_enclosing;
    683 			free(istk);
    684 			initstk = inxt;
    685 			goto again;
    686 		}
    687 		/* XXX: Why is this set to 1 unconditionally? */
    688 		istk->i_remaining = 1;
    689 		break;
    690 	}
    691 
    692 	debug_initstack();
    693 	debug_leave();
    694 }
    695 
    696 static void
    697 check_too_many_initializers(void)
    698 {
    699 
    700 	const initstack_element *istk = initstk;
    701 	if (istk->i_remaining > 0)
    702 		return;
    703 	if (istk->i_array_of_unknown_size || istk->i_seen_named_member)
    704 		return;
    705 
    706 	tspec_t t = istk->i_type->t_tspec;
    707 	if (t == ARRAY) {
    708 		/* too many array initializers, expected %d */
    709 		error(173, istk->i_type->t_dim);
    710 	} else if (t == STRUCT || t == UNION) {
    711 		/* too many struct/union initializers */
    712 		error(172);
    713 	} else {
    714 		/* too many initializers */
    715 		error(174);
    716 	}
    717 	initerr = true;
    718 }
    719 
    720 /*
    721  * Process a '{' in an initializer by starting the initialization of the
    722  * nested data structure, with i_type being the i_subt of the outer
    723  * initialization level.
    724  */
    725 static void
    726 initstack_next_brace(void)
    727 {
    728 
    729 	debug_enter();
    730 	debug_initstack();
    731 
    732 	if (initstk->i_type != NULL && is_scalar(initstk->i_type->t_tspec)) {
    733 		/* invalid initializer type %s */
    734 		error(176, type_name(initstk->i_type));
    735 		initerr = true;
    736 	}
    737 	if (!initerr)
    738 		check_too_many_initializers();
    739 	if (!initerr)
    740 		initstack_push();
    741 	if (!initerr) {
    742 		initstk->i_brace = true;
    743 		debug_named_member();
    744 		debug_step("expecting type '%s'",
    745 		    type_name(initstk->i_type != NULL ? initstk->i_type
    746 			: initstk->i_subt));
    747 	}
    748 
    749 	debug_initstack();
    750 	debug_leave();
    751 }
    752 
    753 static void
    754 initstack_next_nobrace(void)
    755 {
    756 	debug_enter();
    757 
    758 	if (initstk->i_type == NULL && !is_scalar(initstk->i_subt->t_tspec)) {
    759 		/* {}-enclosed initializer required */
    760 		error(181);
    761 		/* XXX: maybe set initerr here */
    762 	}
    763 
    764 	if (!initerr)
    765 		check_too_many_initializers();
    766 
    767 	/*
    768 	 * Make sure an entry with a scalar type is at the top of the stack.
    769 	 *
    770 	 * FIXME: Since C99, an initializer for an object with automatic
    771 	 *  storage need not be a constant expression anymore.  It is
    772 	 *  perfectly fine to initialize a struct with a struct expression,
    773 	 *  see d_struct_init_nested.c for a demonstration.
    774 	 */
    775 	while (!initerr) {
    776 		if ((initstk->i_type != NULL &&
    777 		     is_scalar(initstk->i_type->t_tspec)))
    778 			break;
    779 		initstack_push();
    780 	}
    781 
    782 	debug_initstack();
    783 	debug_leave();
    784 }
    785 
    786 void
    787 init_lbrace(void)
    788 {
    789 	if (initerr)
    790 		return;
    791 
    792 	debug_enter();
    793 	debug_initstack();
    794 
    795 	if ((initsym->s_scl == AUTO || initsym->s_scl == REG) &&
    796 	    initstk->i_enclosing == NULL) {
    797 		if (tflag && !is_scalar(initstk->i_subt->t_tspec))
    798 			/* no automatic aggregate initialization in trad. C */
    799 			warning(188);
    800 	}
    801 
    802 	/*
    803 	 * Remove all entries which cannot be used for further initializers
    804 	 * and do not expect a closing brace.
    805 	 */
    806 	initstack_pop_nobrace();
    807 
    808 	initstack_next_brace();
    809 
    810 	debug_initstack();
    811 	debug_leave();
    812 }
    813 
    814 /*
    815  * Process a '}' in an initializer by finishing the current level of the
    816  * initialization stack.
    817  */
    818 void
    819 init_rbrace(void)
    820 {
    821 	if (initerr)
    822 		return;
    823 
    824 	debug_enter();
    825 	initstack_pop_brace();
    826 	debug_leave();
    827 }
    828 
    829 /* In traditional C, bit-fields can be initialized only by integer constants. */
    830 static void
    831 check_bit_field_init(const tnode_t *ln, tspec_t lt, tspec_t rt)
    832 {
    833 	if (tflag &&
    834 	    is_integer(lt) &&
    835 	    ln->tn_type->t_bitfield &&
    836 	    !is_integer(rt)) {
    837 		/* bit-field initialization is illegal in traditional C */
    838 		warning(186);
    839 	}
    840 }
    841 
    842 static void
    843 check_non_constant_initializer(const tnode_t *tn, scl_t sclass)
    844 {
    845 	if (tn == NULL || tn->tn_op == CON)
    846 		return;
    847 
    848 	sym_t *sym;
    849 	ptrdiff_t offs;
    850 	if (constant_addr(tn, &sym, &offs))
    851 		return;
    852 
    853 	if (sclass == AUTO || sclass == REG) {
    854 		/* non-constant initializer */
    855 		c99ism(177);
    856 	} else {
    857 		/* non-constant initializer */
    858 		error(177);
    859 	}
    860 }
    861 
    862 void
    863 init_using_expr(tnode_t *tn)
    864 {
    865 	tspec_t	lt, rt;
    866 	tnode_t	*ln;
    867 	struct	mbl *tmem;
    868 	scl_t	sclass;
    869 
    870 	debug_enter();
    871 	debug_initstack();
    872 	debug_named_member();
    873 	debug_step("expr:");
    874 	debug_node(tn, debug_ind + 1);
    875 
    876 	if (initerr || tn == NULL) {
    877 		debug_leave();
    878 		return;
    879 	}
    880 
    881 	sclass = initsym->s_scl;
    882 
    883 	/*
    884 	 * Do not test for automatic aggregate initialization. If the
    885 	 * initializer starts with a brace we have the warning already.
    886 	 * If not, an error will be printed that the initializer must
    887 	 * be enclosed by braces.
    888 	 */
    889 
    890 	/*
    891 	 * Local initialization of non-array-types with only one expression
    892 	 * without braces is done by ASSIGN
    893 	 */
    894 	if ((sclass == AUTO || sclass == REG) &&
    895 	    initsym->s_type->t_tspec != ARRAY && initstk->i_enclosing == NULL) {
    896 		debug_step("handing over to ASSIGN");
    897 		ln = new_name_node(initsym, 0);
    898 		ln->tn_type = tduptyp(ln->tn_type);
    899 		ln->tn_type->t_const = false;
    900 		tn = build(ASSIGN, ln, tn);
    901 		expr(tn, false, false, false, false);
    902 		/* XXX: why not clean up the initstack here already? */
    903 		debug_leave();
    904 		return;
    905 	}
    906 
    907 	initstack_pop_nobrace();
    908 
    909 	if (init_array_using_string(tn)) {
    910 		debug_step("after initializing the string:");
    911 		/* XXX: why not clean up the initstack here already? */
    912 		debug_initstack();
    913 		debug_leave();
    914 		return;
    915 	}
    916 
    917 	initstack_next_nobrace();
    918 	if (initerr || tn == NULL) {
    919 		debug_initstack();
    920 		debug_leave();
    921 		return;
    922 	}
    923 
    924 	initstk->i_remaining--;
    925 	debug_step("%d elements remaining", initstk->i_remaining);
    926 
    927 	/* Create a temporary node for the left side. */
    928 	ln = tgetblk(sizeof (tnode_t));
    929 	ln->tn_op = NAME;
    930 	ln->tn_type = tduptyp(initstk->i_type);
    931 	ln->tn_type->t_const = false;
    932 	ln->tn_lvalue = true;
    933 	ln->tn_sym = initsym;		/* better than nothing */
    934 
    935 	tn = cconv(tn);
    936 
    937 	lt = ln->tn_type->t_tspec;
    938 	rt = tn->tn_type->t_tspec;
    939 
    940 	lint_assert(is_scalar(lt));	/* at least before C99 */
    941 
    942 	debug_step("typeok '%s', '%s'",
    943 	    type_name(ln->tn_type), type_name(tn->tn_type));
    944 	if (!typeok(INIT, 0, ln, tn)) {
    945 		debug_initstack();
    946 		debug_leave();
    947 		return;
    948 	}
    949 
    950 	/*
    951 	 * Store the tree memory. This is necessary because otherwise
    952 	 * expr() would free it.
    953 	 */
    954 	tmem = tsave();
    955 	expr(tn, true, false, true, false);
    956 	trestor(tmem);
    957 
    958 	check_bit_field_init(ln, lt, rt);
    959 
    960 	/*
    961 	 * XXX: Is it correct to do this conversion _after_ the typeok above?
    962 	 */
    963 	if (lt != rt || (initstk->i_type->t_bitfield && tn->tn_op == CON))
    964 		tn = convert(INIT, 0, initstk->i_type, tn);
    965 
    966 	check_non_constant_initializer(tn, sclass);
    967 
    968 	debug_initstack();
    969 	debug_leave();
    970 }
    971 
    972 
    973 /* Initialize a character array or wchar_t array with a string literal. */
    974 static bool
    975 init_array_using_string(tnode_t *tn)
    976 {
    977 	tspec_t	t;
    978 	initstack_element *istk;
    979 	int	len;
    980 	strg_t	*strg;
    981 
    982 	if (tn->tn_op != STRING)
    983 		return false;
    984 
    985 	debug_enter();
    986 	debug_initstack();
    987 
    988 	istk = initstk;
    989 	strg = tn->tn_string;
    990 
    991 	/*
    992 	 * Check if we have an array type which can be initialized by
    993 	 * the string.
    994 	 */
    995 	if (istk->i_subt != NULL && istk->i_subt->t_tspec == ARRAY) {
    996 		debug_step("subt array");
    997 		t = istk->i_subt->t_subt->t_tspec;
    998 		if (!((strg->st_tspec == CHAR &&
    999 		       (t == CHAR || t == UCHAR || t == SCHAR)) ||
   1000 		      (strg->st_tspec == WCHAR && t == WCHAR))) {
   1001 			debug_leave();
   1002 			return false;
   1003 		}
   1004 		/* XXX: duplicate code, see below */
   1005 		/* Put the array at top of stack */
   1006 		initstack_push();
   1007 		istk = initstk;
   1008 	} else if (istk->i_type != NULL && istk->i_type->t_tspec == ARRAY) {
   1009 		debug_step("type array");
   1010 		t = istk->i_type->t_subt->t_tspec;
   1011 		if (!((strg->st_tspec == CHAR &&
   1012 		       (t == CHAR || t == UCHAR || t == SCHAR)) ||
   1013 		      (strg->st_tspec == WCHAR && t == WCHAR))) {
   1014 			debug_leave();
   1015 			return false;
   1016 		}
   1017 		/* XXX: duplicate code, see above */
   1018 		/*
   1019 		 * If the array is already partly initialized, we are
   1020 		 * wrong here.
   1021 		 */
   1022 		if (istk->i_remaining != istk->i_type->t_dim)
   1023 			debug_leave();
   1024 			return false;
   1025 	} else {
   1026 		debug_leave();
   1027 		return false;
   1028 	}
   1029 
   1030 	/* Get length without trailing NUL character. */
   1031 	len = strg->st_len;
   1032 
   1033 	if (istk->i_array_of_unknown_size) {
   1034 		istk->i_array_of_unknown_size = false;
   1035 		istk->i_type->t_dim = len + 1;
   1036 		setcomplete(istk->i_type, true);
   1037 	} else {
   1038 		if (istk->i_type->t_dim < len) {
   1039 			/* non-null byte ignored in string initializer */
   1040 			warning(187);
   1041 		}
   1042 	}
   1043 
   1044 	/* In every case the array is initialized completely. */
   1045 	istk->i_remaining = 0;
   1046 
   1047 	debug_initstack();
   1048 	debug_leave();
   1049 	return true;
   1050 }
   1051