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