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