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