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