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