out: exit if there is no room for more relocations or symbols
[neatcc/cc.git] / ncc.c
blob365813011ad6414d93f5b053d394d38d24ea7292
1 /*
2 * neatcc - the neatcc compiler
4 * Copyright (C) 2010-2014 Ali Gholami Rudi
6 * This program is released under the Modified BSD license.
7 */
8 /*
9 * neatcc parser
11 * The parser reads tokens from the tokenizer (tok_*) and calls the
12 * appropriate code generation functions (o_*). The generator
13 * maintains a stack of values pushed via, for instance, o_num()
14 * and generates the necessary code for the accesses to the items
15 * in this stack, like o_bop() for performing a binary operations
16 * on the top two items of the stack. The parser maintains the
17 * types of values pushed to the generator stack in its type stack
18 * (ts_*). For instance, for binary operations two types are
19 * popped first and the resulting type is pushed to the type stack
20 * (ts_binop()).
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <stdio.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include "gen.h"
32 #include "ncc.h"
33 #include "out.h"
34 #include "tok.h"
36 static int nogen; /* do not generate code, if set */
37 #define o_bop(op) {if (!nogen) o_bop(op);}
38 #define o_uop(op) {if (!nogen) o_uop(op);}
39 #define o_cast(bt) {if (!nogen) o_cast(bt);}
40 #define o_memcpy() {if (!nogen) o_memcpy();}
41 #define o_memset() {if (!nogen) o_memset();}
42 #define o_call(argc, ret) {if (!nogen) o_call(argc, ret);}
43 #define o_ret(ret) {if (!nogen) o_ret(ret);}
44 #define o_assign(bt) {if (!nogen) o_assign(bt);}
45 #define o_deref(bt) {if (!nogen) o_deref(bt);}
46 #define o_load() {if (!nogen) o_load();}
47 #define o_popnum(c) (nogen ? 0 : o_popnum(c))
48 #define o_num(n) {if (!nogen) o_num(n);}
49 #define o_local(addr) {if (!nogen) o_local(addr);}
50 #define o_sym(sym) {if (!nogen) o_sym(sym);}
51 #define o_tmpdrop(n) {if (!nogen) o_tmpdrop(n);}
52 #define o_tmpswap() {if (!nogen) o_tmpswap();}
53 #define o_tmpcopy() {if (!nogen) o_tmpcopy();}
54 #define o_label(id) {if (!nogen) o_label(id);}
55 #define o_jz(id) {if (!nogen) o_jz(id);}
56 #define o_jnz(id) {if (!nogen) o_jnz(id);}
57 #define o_jmp(id) {if (!nogen) o_jmp(id);}
58 #define o_fork() {if (!nogen) o_fork();}
59 #define o_forkpush() {if (!nogen) o_forkpush();}
60 #define o_forkjoin() {if (!nogen) o_forkjoin();}
62 #define ALIGN(x, a) (((x) + (a) - 1) & ~((a) - 1))
63 #define MIN(a, b) ((a) < (b) ? (a) : (b))
65 #define TYPE_BT(t) ((t)->ptr ? LONGSZ : (t)->bt)
66 #define TYPE_SZ(t) ((t)->ptr ? LONGSZ : (t)->bt & BT_SZMASK)
67 #define TYPE_VOID(t) (!(t)->bt && !(t)->flags && !(t)->ptr)
69 /* type->flag values */
70 #define T_ARRAY 0x01
71 #define T_STRUCT 0x02
72 #define T_FUNC 0x04
74 /* variable definition flags */
75 #define F_STATIC 0x01
76 #define F_EXTERN 0x02
78 struct type {
79 unsigned bt;
80 unsigned flags;
81 int ptr;
82 int id; /* for structs, functions and arrays */
83 int addr; /* the address is passed to gen.c; deref for value */
86 /* type stack */
87 static struct type ts[NTMPS];
88 static int nts;
90 static void ts_push_bt(unsigned bt)
92 ts[nts].ptr = 0;
93 ts[nts].flags = 0;
94 ts[nts].addr = 0;
95 ts[nts++].bt = bt;
98 static void ts_push(struct type *t)
100 struct type *d = &ts[nts++];
101 memcpy(d, t, sizeof(*t));
104 static void ts_push_addr(struct type *t)
106 ts_push(t);
107 ts[nts - 1].addr = 1;
110 static void ts_pop(struct type *type)
112 nts--;
113 if (type)
114 *type = ts[nts];
117 void err(char *fmt, ...)
119 va_list ap;
120 char msg[512];
121 va_start(ap, fmt);
122 vsprintf(msg, fmt, ap);
123 va_end(ap);
124 die("%s: %s", cpp_loc(tok_addr()), msg);
127 struct name {
128 char name[NAMELEN];
129 char elfname[NAMELEN]; /* local elf name for function static variables */
130 struct type type;
131 long addr; /* local stack offset, global data addr, struct offset */
134 static struct name locals[NLOCALS];
135 static int nlocals;
136 static struct name globals[NGLOBALS];
137 static int nglobals;
139 static void local_add(struct name *name)
141 if (nlocals >= NLOCALS)
142 err("nomem: NLOCALS reached!\n");
143 memcpy(&locals[nlocals++], name, sizeof(*name));
146 static int local_find(char *name)
148 int i;
149 for (i = nlocals - 1; i >= 0; --i)
150 if (!strcmp(locals[i].name, name))
151 return i;
152 return -1;
155 static int global_find(char *name)
157 int i;
158 for (i = nglobals - 1; i >= 0; i--)
159 if (!strcmp(name, globals[i].name))
160 return i;
161 return -1;
164 static void global_add(struct name *name)
166 if (nglobals >= NGLOBALS)
167 err("nomem: NGLOBALS reached!\n");
168 memcpy(&globals[nglobals++], name, sizeof(*name));
171 #define LABEL() (++label)
173 static int label; /* last used label id */
174 static int l_break; /* current break label */
175 static int l_cont; /* current continue label */
177 static struct enumval {
178 char name[NAMELEN];
179 int n;
180 } enums[NENUMS];
181 static int nenums;
183 static void enum_add(char *name, int val)
185 struct enumval *ev = &enums[nenums++];
186 if (nenums >= NENUMS)
187 err("nomem: NENUMS reached!\n");
188 strcpy(ev->name, name);
189 ev->n = val;
192 static int enum_find(int *val, char *name)
194 int i;
195 for (i = nenums - 1; i >= 0; --i)
196 if (!strcmp(name, enums[i].name)) {
197 *val = enums[i].n;
198 return 0;
200 return 1;
203 static struct typdefinfo {
204 char name[NAMELEN];
205 struct type type;
206 } typedefs[NTYPEDEFS];
207 static int ntypedefs;
209 static void typedef_add(char *name, struct type *type)
211 struct typdefinfo *ti = &typedefs[ntypedefs++];
212 if (ntypedefs >= NTYPEDEFS)
213 err("nomem: NTYPEDEFS reached!\n");
214 strcpy(ti->name, name);
215 memcpy(&ti->type, type, sizeof(*type));
218 static int typedef_find(char *name)
220 int i;
221 for (i = ntypedefs - 1; i >= 0; --i)
222 if (!strcmp(name, typedefs[i].name))
223 return i;
224 return -1;
227 static struct array {
228 struct type type;
229 int n;
230 } arrays[NARRAYS];
231 static int narrays;
233 static int array_add(struct type *type, int n)
235 struct array *a = &arrays[narrays++];
236 if (narrays >= NARRAYS)
237 err("nomem: NARRAYS reached!\n");
238 memcpy(&a->type, type, sizeof(*type));
239 a->n = n;
240 return a - arrays;
243 static void array2ptr(struct type *t)
245 if (t->flags & T_ARRAY && !t->ptr) {
246 memcpy(t, &arrays[t->id].type, sizeof(*t));
247 t->ptr++;
251 static struct structinfo {
252 char name[NAMELEN];
253 struct name fields[NFIELDS];
254 int nfields;
255 int isunion;
256 int size;
257 } structs[NSTRUCTS];
258 static int nstructs;
260 static int struct_find(char *name, int isunion)
262 int i;
263 for (i = nstructs - 1; i >= 0; --i)
264 if (*structs[i].name && !strcmp(name, structs[i].name) &&
265 structs[i].isunion == isunion)
266 return i;
267 i = nstructs++;
268 if (nstructs >= NSTRUCTS)
269 err("nomem: NSTRUCTS reached!\n");
270 memset(&structs[i], 0, sizeof(structs[i]));
271 strcpy(structs[i].name, name);
272 structs[i].isunion = isunion;
273 return i;
276 static struct name *struct_field(int id, char *name)
278 struct structinfo *si = &structs[id];
279 int i;
280 for (i = 0; i < si->nfields; i++)
281 if (!strcmp(name, si->fields[i].name))
282 return &si->fields[i];
283 err("field not found\n");
284 return NULL;
287 /* return t's size */
288 static int type_totsz(struct type *t)
290 if (t->ptr)
291 return LONGSZ;
292 if (t->flags & T_ARRAY)
293 return arrays[t->id].n * type_totsz(&arrays[t->id].type);
294 return t->flags & T_STRUCT ? structs[t->id].size : BT_SZ(t->bt);
297 /* return t's dereferenced size */
298 static unsigned type_szde(struct type *t)
300 struct type de = *t;
301 array2ptr(&de);
302 de.ptr--;
303 return type_totsz(&de);
306 /* dereference stack top if t->addr (ie. address is pushed to gen.c) */
307 static void ts_de(int deref)
309 struct type *t = &ts[nts - 1];
310 array2ptr(t);
311 if (deref && t->addr && (t->ptr || !(t->flags & T_FUNC)))
312 o_deref(TYPE_BT(t));
313 t->addr = 0;
316 /* pop stack pop to *t and dereference if t->addr */
317 static void ts_pop_de(struct type *t)
319 ts_de(1);
320 ts_pop(t);
323 /* pop the top 2 stack values and dereference them if t->addr */
324 static void ts_pop_de2(struct type *t1, struct type *t2)
326 ts_pop_de(t1);
327 o_tmpswap();
328 ts_pop_de(t2);
329 o_tmpswap();
332 static int tok_jmp(int tok)
334 if (tok_see() != tok)
335 return 1;
336 tok_get();
337 return 0;
340 static void tok_expect(int tok)
342 if (tok_get() != tok)
343 err("syntax error\n");
346 /* the result of a binary operation on variables of type bt1 and bt2 */
347 static unsigned bt_op(unsigned bt1, unsigned bt2)
349 unsigned s1 = BT_SZ(bt1);
350 unsigned s2 = BT_SZ(bt2);
351 return ((bt1 | bt2) & BT_SIGNED) | (s1 > s2 ? s1 : s2);
354 /* push the result of a binary operation on the type stack */
355 static void ts_binop(int op)
357 struct type t1, t2;
358 int bt;
359 ts_pop_de2(&t1, &t2);
360 if (op == O_DIV || op == O_MOD)
361 bt = TYPE_BT(&t2);
362 else
363 bt = bt_op(TYPE_BT(&t1), TYPE_BT(&t2));
364 o_bop(op | (bt & BT_SIGNED ? O_SIGNED : 0));
365 ts_push_bt(bt);
368 /* push the result of an additive binary operation on the type stack */
369 static void ts_addop(int op)
371 struct type t1, t2;
372 ts_pop_de2(&t1, &t2);
373 if (!t1.ptr && !t2.ptr) {
374 o_bop(op);
375 ts_push_bt(bt_op(TYPE_BT(&t1), TYPE_BT(&t2)));
376 return;
378 if (t1.ptr && !t2.ptr)
379 o_tmpswap();
380 if (!t1.ptr && t2.ptr)
381 if (type_szde(&t2) > 1) {
382 o_num(type_szde(&t2));
383 o_bop(O_MUL);
385 if (t1.ptr && !t2.ptr)
386 o_tmpswap();
387 o_bop(op);
388 if (t1.ptr && t2.ptr) {
389 int sz = type_szde(&t1);
390 if (sz > 1) {
391 o_num(sz);
392 o_bop(O_DIV);
394 ts_push_bt(4 | BT_SIGNED);
395 } else {
396 ts_push(t1.ptr ? &t1 : &t2);
400 /* function prototypes for parsing function and variable declarations */
401 static int readname(struct type *main, char *name, struct type *base);
402 static int readtype(struct type *type);
403 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
404 void *data);
405 static int readdefs_int(void (*def)(void *data, struct name *name, unsigned flags),
406 void *data);
408 /* function prototypes for parsing initializer expressions */
409 static int initsize(void);
410 static void initexpr(struct type *t, int off, void *obj,
411 void (*set)(void *obj, int off, struct type *t));
413 static int type_alignment(struct type *t)
415 if (t->flags & T_ARRAY && !t->ptr)
416 return type_alignment(&arrays[t->id].type);
417 if (t->flags & T_STRUCT && !t->ptr)
418 return type_alignment(&structs[t->id].fields[0].type);
419 return MIN(LONGSZ, type_totsz(t));
422 static void structdef(void *data, struct name *name, unsigned flags)
424 struct structinfo *si = data;
425 if (si->isunion) {
426 name->addr = 0;
427 if (si->size < type_totsz(&name->type))
428 si->size = type_totsz(&name->type);
429 } else {
430 struct type *t = &name->type;
431 int alignment = type_alignment(t);
432 if (t->flags & T_ARRAY && !t->ptr)
433 alignment = MIN(LONGSZ, type_totsz(&arrays[t->id].type));
434 si->size = ALIGN(si->size, alignment);
435 name->addr = si->size;
436 si->size += type_totsz(&name->type);
438 memcpy(&si->fields[si->nfields++], name, sizeof(*name));
441 static int struct_create(char *name, int isunion)
443 int id = struct_find(name, isunion);
444 struct structinfo *si = &structs[id];
445 tok_expect('{');
446 while (tok_jmp('}')) {
447 readdefs(structdef, si);
448 tok_expect(';');
450 return id;
453 static void readexpr(void);
455 static void enum_create(void)
457 long n = 0;
458 tok_expect('{');
459 while (tok_jmp('}')) {
460 char name[NAMELEN];
461 tok_expect(TOK_NAME);
462 strcpy(name, tok_id());
463 if (!tok_jmp('=')) {
464 readexpr();
465 ts_pop_de(NULL);
466 if (o_popnum(&n))
467 err("const expr expected!\n");
469 enum_add(name, n++);
470 tok_jmp(',');
474 /* used to differentiate labels from case and cond exprs */
475 static int ncexpr;
476 static int caseexpr;
478 static void readpre(void);
480 static char *tmp_str(char *buf, int len)
482 static char name[NAMELEN];
483 static int id;
484 sprintf(name, "__neatcc.s%d", id++);
485 o_dscpy(o_dsnew(name, len, 0), buf, len);
486 return name;
489 static void readprimary(void)
491 if (!tok_jmp(TOK_NUM)) {
492 long n;
493 int bt = tok_num(&n);
494 ts_push_bt(bt);
495 o_num(n);
496 return;
498 if (!tok_jmp(TOK_STR)) {
499 struct type t = {}; /* char type inside the arrays */
500 struct type a = {}; /* the char array type */
501 char *buf;
502 int len;
503 tok_str(&buf, &len);
504 t.bt = 1 | BT_SIGNED;
505 a.id = array_add(&t, len);
506 a.flags = T_ARRAY;
507 ts_push(&a);
508 o_sym(tmp_str(buf, len));
509 return;
511 if (!tok_jmp(TOK_NAME)) {
512 struct name unkn = {""};
513 char *name = unkn.name;
514 int n;
515 strcpy(name, tok_id());
516 /* don't search for labels here */
517 if (!ncexpr && !caseexpr && tok_see() == ':')
518 return;
519 if ((n = local_find(name)) != -1) {
520 struct name *l = &locals[n];
521 o_local(l->addr);
522 ts_push_addr(&l->type);
523 return;
525 if ((n = global_find(name)) != -1) {
526 struct name *g = &globals[n];
527 o_sym(*g->elfname ? g->elfname : g->name);
528 ts_push_addr(&g->type);
529 return;
531 if (!enum_find(&n, name)) {
532 ts_push_bt(4 | BT_SIGNED);
533 o_num(n);
534 return;
536 if (tok_see() != '(')
537 err("unknown symbol <%s>\n", name);
538 global_add(&unkn);
539 ts_push_bt(LONGSZ);
540 o_sym(unkn.name);
541 return;
543 if (!tok_jmp('(')) {
544 struct type t;
545 if (!readtype(&t)) {
546 struct type o;
547 tok_expect(')');
548 readpre();
549 ts_pop_de(&o);
550 ts_push(&t);
551 if (!t.ptr || !o.ptr)
552 o_cast(TYPE_BT(&t));
553 } else {
554 readexpr();
555 while (tok_jmp(')')) {
556 tok_expect(',');
557 ts_pop(NULL);
558 o_tmpdrop(1);
559 readexpr();
562 return;
566 static void arrayderef(void)
568 struct type t;
569 int sz;
570 ts_pop_de(NULL);
571 ts_pop(&t);
572 if (!(t.flags & T_ARRAY && !t.ptr) && t.addr) {
573 o_tmpswap();
574 o_deref(TYPE_BT(&t));
575 o_tmpswap();
577 array2ptr(&t);
578 t.ptr--;
579 sz = type_totsz(&t);
580 t.addr = 1;
581 if (sz > 1) {
582 o_num(sz);
583 o_bop(O_MUL);
585 o_bop(O_ADD);
586 ts_push(&t);
589 static void inc_post(int op)
591 struct type t = ts[nts - 1];
592 /* pushing the value before inc */
593 o_tmpcopy();
594 ts_de(1);
595 o_load();
596 o_tmpswap();
598 /* increment by 1 or pointer size */
599 o_tmpcopy();
600 ts_push(&t);
601 ts_pop_de(&t);
602 o_num(t.ptr > 0 ? type_szde(&t) : 1);
603 o_bop(op);
605 /* assign back */
606 o_assign(TYPE_BT(&t));
607 o_tmpdrop(1);
610 static void readfield(void)
612 struct name *field;
613 struct type t;
614 tok_expect(TOK_NAME);
615 ts_pop(&t);
616 array2ptr(&t);
617 field = struct_field(t.id, tok_id());
618 if (field->addr) {
619 o_num(field->addr);
620 o_bop(O_ADD);
622 ts_push_addr(&field->type);
625 static struct funcinfo {
626 struct type args[NARGS];
627 struct type ret;
628 int nargs;
629 int varg;
630 /* function and argument names; useful only when defining */
631 char argnames[NARGS][NAMELEN];
632 char name[NAMELEN];
633 } funcs[NFUNCS];
634 static int nfuncs;
636 static int func_create(struct type *ret, char *name, char argnames[][NAMELEN],
637 struct type *args, int nargs, int varg)
639 struct funcinfo *fi = &funcs[nfuncs++];
640 int i;
641 if (nfuncs >= NFUNCS)
642 err("nomem: NFUNCS reached!\n");
643 memcpy(&fi->ret, ret, sizeof(*ret));
644 for (i = 0; i < nargs; i++)
645 memcpy(&fi->args[i], &args[i], sizeof(*ret));
646 fi->nargs = nargs;
647 fi->varg = varg;
648 strcpy(fi->name, name ? name : "");
649 for (i = 0; i < nargs; i++)
650 strcpy(fi->argnames[i], argnames[i]);
651 return fi - funcs;
654 static void readcall(void)
656 struct type t;
657 struct funcinfo *fi;
658 int argc = 0;
659 ts_pop(&t);
660 if (t.flags & T_FUNC && t.ptr > 0)
661 o_deref(LONGSZ);
662 fi = t.flags & T_FUNC ? &funcs[t.id] : NULL;
663 if (tok_see() != ')') {
664 do {
665 readexpr();
666 ts_pop_de(NULL);
667 argc++;
668 } while (!tok_jmp(','));
670 tok_expect(')');
671 o_call(argc, fi ? TYPE_BT(&fi->ret) : 4 | BT_SIGNED);
672 if (fi) {
673 if (TYPE_BT(&fi->ret))
674 o_cast(TYPE_BT(&fi->ret));
675 ts_push(&fi->ret);
676 } else {
677 ts_push_bt(4 | BT_SIGNED);
681 static void readpost(void)
683 readprimary();
684 while (1) {
685 if (!tok_jmp('[')) {
686 readexpr();
687 tok_expect(']');
688 arrayderef();
689 continue;
691 if (!tok_jmp('(')) {
692 readcall();
693 continue;
695 if (!tok_jmp(TOK2("++"))) {
696 inc_post(O_ADD);
697 continue;
699 if (!tok_jmp(TOK2("--"))) {
700 inc_post(O_SUB);
701 continue;
703 if (!tok_jmp('.')) {
704 readfield();
705 continue;
707 if (!tok_jmp(TOK2("->"))) {
708 ts_de(1);
709 readfield();
710 continue;
712 break;
716 static void inc_pre(int op)
718 struct type t;
719 readpre();
720 /* copy the destination */
721 o_tmpcopy();
722 ts_push(&ts[nts - 1]);
723 /* increment by 1 or pointer size */
724 ts_pop_de(&t);
725 o_num(t.ptr > 0 ? type_szde(&t) : 1);
726 o_bop(op);
727 /* assign the result */
728 o_assign(TYPE_BT(&t));
729 ts_de(0);
732 static void readpre(void)
734 if (!tok_jmp('&')) {
735 struct type type;
736 readpre();
737 ts_pop(&type);
738 if (!type.addr)
739 err("cannot use the address\n");
740 type.ptr++;
741 type.addr = 0;
742 ts_push(&type);
743 return;
745 if (!tok_jmp('*')) {
746 struct type t;
747 readpre();
748 ts_pop(&t);
749 array2ptr(&t);
750 if (!t.ptr)
751 err("dereferencing non-pointer\n");
752 if (t.addr)
753 o_deref(TYPE_BT(&t));
754 t.ptr--;
755 t.addr = 1;
756 ts_push(&t);
757 return;
759 if (!tok_jmp('!')) {
760 readpre();
761 ts_pop_de(NULL);
762 o_uop(O_LNOT);
763 ts_push_bt(4 | BT_SIGNED);
764 return;
766 if (!tok_jmp('+')) {
767 readpre();
768 return;
770 if (!tok_jmp('-')) {
771 readpre();
772 ts_de(1);
773 o_uop(O_NEG);
774 return;
776 if (!tok_jmp('~')) {
777 readpre();
778 ts_de(1);
779 o_uop(O_NOT);
780 return;
782 if (!tok_jmp(TOK2("++"))) {
783 inc_pre(O_ADD);
784 return;
786 if (!tok_jmp(TOK2("--"))) {
787 inc_pre(O_SUB);
788 return;
790 if (!tok_jmp(TOK_SIZEOF)) {
791 struct type t;
792 int op = !tok_jmp('(');
793 if (readtype(&t)) {
794 nogen++;
795 if (op)
796 readexpr();
797 else
798 readpre();
799 nogen--;
800 ts_pop(&t);
802 ts_push_bt(4);
803 o_num(type_totsz(&t));
804 if (op)
805 tok_expect(')');
806 return;
808 readpost();
811 static void readmul(void)
813 readpre();
814 while (1) {
815 if (!tok_jmp('*')) {
816 readpre();
817 ts_binop(O_MUL);
818 continue;
820 if (!tok_jmp('/')) {
821 readpre();
822 ts_binop(O_DIV);
823 continue;
825 if (!tok_jmp('%')) {
826 readpre();
827 ts_binop(O_MOD);
828 continue;
830 break;
834 static void readadd(void)
836 readmul();
837 while (1) {
838 if (!tok_jmp('+')) {
839 readmul();
840 ts_addop(O_ADD);
841 continue;
843 if (!tok_jmp('-')) {
844 readmul();
845 ts_addop(O_SUB);
846 continue;
848 break;
852 static void shift(int op)
854 struct type t;
855 readadd();
856 ts_pop_de2(NULL, &t);
857 o_bop(op | (BT_SIGNED & TYPE_BT(&t) ? O_SIGNED : 0));
858 ts_push_bt(TYPE_BT(&t));
861 static void readshift(void)
863 readadd();
864 while (1) {
865 if (!tok_jmp(TOK2("<<"))) {
866 shift(O_SHL);
867 continue;
869 if (!tok_jmp(TOK2(">>"))) {
870 shift(O_SHR);
871 continue;
873 break;
877 static void cmp(int op)
879 struct type t1, t2;
880 int bt;
881 readshift();
882 ts_pop_de2(&t1, &t2);
883 bt = bt_op(TYPE_BT(&t1), TYPE_BT(&t2));
884 o_bop(op | (bt & BT_SIGNED ? O_SIGNED : 0));
885 ts_push_bt(4 | BT_SIGNED);
888 static void readcmp(void)
890 readshift();
891 while (1) {
892 if (!tok_jmp('<')) {
893 cmp(O_LT);
894 continue;
896 if (!tok_jmp('>')) {
897 cmp(O_GT);
898 continue;
900 if (!tok_jmp(TOK2("<="))) {
901 cmp(O_LE);
902 continue;
904 if (!tok_jmp(TOK2(">="))) {
905 cmp(O_GE);
906 continue;
908 break;
912 static void eq(int op)
914 readcmp();
915 ts_pop_de2(NULL, NULL);
916 o_bop(op);
917 ts_push_bt(4 | BT_SIGNED);
920 static void readeq(void)
922 readcmp();
923 while (1) {
924 if (!tok_jmp(TOK2("=="))) {
925 eq(O_EQ);
926 continue;
928 if (!tok_jmp(TOK2("!="))) {
929 eq(O_NEQ);
930 continue;
932 break;
936 static void readbitand(void)
938 readeq();
939 while (!tok_jmp('&')) {
940 readeq();
941 ts_binop(O_AND);
945 static void readxor(void)
947 readbitand();
948 while (!tok_jmp('^')) {
949 readbitand();
950 ts_binop(O_XOR);
954 static void readbitor(void)
956 readxor();
957 while (!tok_jmp('|')) {
958 readxor();
959 ts_binop(O_OR);
963 static void readand(void)
965 int l_out, l_fail;
966 readbitor();
967 if (tok_see() != TOK2("&&"))
968 return;
969 l_out = LABEL();
970 l_fail = LABEL();
971 o_fork();
972 ts_pop_de(NULL);
973 o_jz(l_fail);
974 while (!tok_jmp(TOK2("&&"))) {
975 readbitor();
976 ts_pop_de(NULL);
977 o_jz(l_fail);
979 o_num(1);
980 o_forkpush();
981 o_jmp(l_out);
982 o_label(l_fail);
983 o_num(0);
984 o_forkpush();
985 o_forkjoin();
986 o_label(l_out);
987 ts_push_bt(4 | BT_SIGNED);
990 static void reador(void)
992 int l_pass, l_end;
993 readand();
994 if (tok_see() != TOK2("||"))
995 return;
996 l_pass = LABEL();
997 l_end = LABEL();
998 o_fork();
999 ts_pop_de(NULL);
1000 o_jnz(l_pass);
1001 while (!tok_jmp(TOK2("||"))) {
1002 readand();
1003 ts_pop_de(NULL);
1004 o_jnz(l_pass);
1006 o_num(0);
1007 o_forkpush();
1008 o_jmp(l_end);
1009 o_label(l_pass);
1010 o_num(1);
1011 o_forkpush();
1012 o_forkjoin();
1013 o_label(l_end);
1014 ts_push_bt(4 | BT_SIGNED);
1017 static void readcexpr(void);
1019 static int readcexpr_const(void)
1021 long c;
1022 if (o_popnum(&c))
1023 return -1;
1024 if (!c)
1025 nogen++;
1026 readcexpr();
1027 /* both branches yield the same type; so ignore the first */
1028 ts_pop_de(NULL);
1029 tok_expect(':');
1030 if (c)
1031 nogen++;
1032 else
1033 nogen--;
1034 readcexpr();
1035 /* making sure t->addr == 0 on both branches */
1036 ts_de(1);
1037 if (c)
1038 nogen--;
1039 return 0;
1042 static void readcexpr(void)
1044 reador();
1045 if (tok_jmp('?'))
1046 return;
1047 ncexpr++;
1048 ts_pop_de(NULL);
1049 o_fork();
1050 if (readcexpr_const()) {
1051 int l_fail = LABEL();
1052 int l_end = LABEL();
1053 struct type ret;
1054 o_jz(l_fail);
1055 readcexpr();
1056 /* both branches yield the same type; so ignore the first */
1057 ts_pop_de(&ret);
1058 if (!TYPE_VOID(&ret))
1059 o_forkpush();
1060 o_jmp(l_end);
1062 tok_expect(':');
1063 o_label(l_fail);
1064 readcexpr();
1065 /* making sure t->addr == 0 on both branches */
1066 ts_de(1);
1067 if (!TYPE_VOID(&ret)) {
1068 o_forkpush();
1069 o_forkjoin();
1071 o_label(l_end);
1073 ncexpr--;
1076 static void opassign(int op, int ptrop)
1078 struct type t = ts[nts - 1];
1079 o_tmpcopy();
1080 ts_push(&t);
1081 readexpr();
1082 if (op == O_ADD || op == O_SUB)
1083 ts_addop(op);
1084 else
1085 ts_binop(op);
1086 o_assign(TYPE_BT(&ts[nts - 2]));
1087 ts_pop(NULL);
1088 ts_de(0);
1091 static void doassign(void)
1093 struct type t = ts[nts - 1];
1094 if (!t.ptr && t.flags & T_STRUCT) {
1095 ts_pop(NULL);
1096 o_num(type_totsz(&t));
1097 o_memcpy();
1098 } else {
1099 ts_pop_de(NULL);
1100 o_assign(TYPE_BT(&ts[nts - 1]));
1101 ts_de(0);
1105 static void readexpr(void)
1107 readcexpr();
1108 if (!tok_jmp('=')) {
1109 readexpr();
1110 doassign();
1111 return;
1113 if (!tok_jmp(TOK2("+="))) {
1114 opassign(O_ADD, 1);
1115 return;
1117 if (!tok_jmp(TOK2("-="))) {
1118 opassign(O_SUB, 1);
1119 return;
1121 if (!tok_jmp(TOK2("*="))) {
1122 opassign(O_MUL, 0);
1123 return;
1125 if (!tok_jmp(TOK2("/="))) {
1126 opassign(O_DIV, 0);
1127 return;
1129 if (!tok_jmp(TOK2("%="))) {
1130 opassign(O_MOD, 0);
1131 return;
1133 if (!tok_jmp(TOK3("<<="))) {
1134 opassign(O_SHL, 0);
1135 return;
1137 if (!tok_jmp(TOK3(">>="))) {
1138 opassign(O_SHR, 0);
1139 return;
1141 if (!tok_jmp(TOK3("&="))) {
1142 opassign(O_AND, 0);
1143 return;
1145 if (!tok_jmp(TOK3("|="))) {
1146 opassign(O_OR, 0);
1147 return;
1149 if (!tok_jmp(TOK3("^="))) {
1150 opassign(O_XOR, 0);
1151 return;
1155 static void readestmt(void)
1157 do {
1158 o_tmpdrop(-1);
1159 nts = 0;
1160 readexpr();
1161 } while (!tok_jmp(','));
1164 #define F_GLOBAL(flags) (!((flags) & F_STATIC))
1166 static void globalinit(void *obj, int off, struct type *t)
1168 struct name *name = obj;
1169 char *elfname = *name->elfname ? name->elfname : name->name;
1170 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1171 struct type *t_de = &arrays[t->id].type;
1172 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1173 char *buf;
1174 int len;
1175 tok_expect(TOK_STR);
1176 tok_str(&buf, &len);
1177 o_dscpy(name->addr + off, buf, len);
1178 return;
1181 readexpr();
1182 o_dsset(elfname, off, TYPE_BT(t));
1183 ts_pop(NULL);
1186 static void readfunc(struct name *name, int flags);
1188 static void globaldef(void *data, struct name *name, unsigned flags)
1190 struct type *t = &name->type;
1191 char *elfname = *name->elfname ? name->elfname : name->name;
1192 int sz;
1193 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1194 if (~flags & F_EXTERN)
1195 arrays[t->id].n = initsize();
1196 sz = type_totsz(t);
1197 if (!(flags & F_EXTERN) && (!(t->flags & T_FUNC) || t->ptr)) {
1198 if (tok_see() == '=')
1199 name->addr = o_dsnew(elfname, sz, F_GLOBAL(flags));
1200 else
1201 o_bsnew(elfname, sz, F_GLOBAL(flags));
1203 global_add(name);
1204 if (!tok_jmp('='))
1205 initexpr(t, 0, name, globalinit);
1206 if (tok_see() == '{' && name->type.flags & T_FUNC)
1207 readfunc(name, flags);
1210 /* generate the address of local + off */
1211 static void o_localoff(long addr, int off)
1213 o_local(addr);
1214 if (off) {
1215 o_num(off);
1216 o_bop(O_ADD);
1220 static void localinit(void *obj, int off, struct type *t)
1222 long addr = *(long *) obj;
1223 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1224 struct type *t_de = &arrays[t->id].type;
1225 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1226 char *buf;
1227 int len;
1228 tok_expect(TOK_STR);
1229 tok_str(&buf, &len);
1230 o_localoff(addr, off);
1231 o_sym(tmp_str(buf, len));
1232 o_num(len);
1233 o_memcpy();
1234 o_tmpdrop(1);
1235 return;
1238 o_localoff(addr, off);
1239 ts_push(t);
1240 readexpr();
1241 doassign();
1242 ts_pop(NULL);
1243 o_tmpdrop(1);
1246 /* current function name */
1247 static char func_name[NAMELEN];
1249 static void localdef(void *data, struct name *name, unsigned flags)
1251 struct type *t = &name->type;
1252 if ((flags & F_EXTERN) || ((t->flags & T_FUNC) && !t->ptr)) {
1253 global_add(name);
1254 return;
1256 if (flags & F_STATIC) {
1257 sprintf(name->elfname, "__neatcc.%s.%s", func_name, name->name);
1258 globaldef(data, name, flags);
1259 return;
1261 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1262 arrays[t->id].n = initsize();
1263 name->addr = o_mklocal(type_totsz(&name->type));
1264 local_add(name);
1265 if (!tok_jmp('=')) {
1266 if (t->flags & (T_ARRAY | T_STRUCT) && !t->ptr) {
1267 o_local(name->addr);
1268 o_num(0);
1269 o_num(type_totsz(t));
1270 o_memset();
1271 o_tmpdrop(1);
1273 initexpr(t, 0, &name->addr, localinit);
1277 static void typedefdef(void *data, struct name *name, unsigned flags)
1279 typedef_add(name->name, &name->type);
1282 static void readstmt(void);
1284 static void readswitch(void)
1286 int o_break = l_break;
1287 long val_addr = o_mklocal(LONGSZ);
1288 struct type t;
1289 int ncases = 0; /* number of case labels */
1290 int l_failed = LABEL(); /* address of last failed jmp */
1291 int l_matched = LABEL(); /* address of last walk through jmp */
1292 int l_default = 0; /* default case label */
1293 l_break = LABEL();
1294 tok_expect('(');
1295 readexpr();
1296 ts_pop_de(&t);
1297 o_local(val_addr);
1298 o_tmpswap();
1299 o_assign(TYPE_BT(&t));
1300 ts_de(0);
1301 o_tmpdrop(1);
1302 tok_expect(')');
1303 tok_expect('{');
1304 while (tok_jmp('}')) {
1305 if (tok_see() != TOK_CASE && tok_see() != TOK_DEFAULT) {
1306 readstmt();
1307 continue;
1309 if (ncases)
1310 o_jmp(l_matched);
1311 if (tok_get() == TOK_CASE) {
1312 o_label(l_failed);
1313 l_failed = LABEL();
1314 caseexpr = 1;
1315 readexpr();
1316 ts_pop_de(NULL);
1317 caseexpr = 0;
1318 o_local(val_addr);
1319 o_deref(TYPE_BT(&t));
1320 o_bop(O_EQ);
1321 o_jz(l_failed);
1322 o_tmpdrop(1);
1323 } else {
1324 if (!ncases)
1325 o_jmp(l_failed);
1326 l_default = LABEL();
1327 o_label(l_default);
1329 tok_expect(':');
1330 o_label(l_matched);
1331 l_matched = LABEL();
1332 ncases++;
1334 o_rmlocal(val_addr, LONGSZ);
1335 o_jmp(l_break);
1336 o_label(l_failed);
1337 if (l_default)
1338 o_jmp(l_default);
1339 o_label(l_break);
1340 l_break = o_break;
1343 static char label_name[NLABELS][NAMELEN];
1344 static int label_ids[NLABELS];
1345 static int nlabels;
1347 static int label_id(char *name)
1349 int i;
1350 for (i = nlabels - 1; i >= 0; --i)
1351 if (!strcmp(label_name[i], name))
1352 return label_ids[i];
1353 strcpy(label_name[nlabels], name);
1354 label_ids[nlabels] = LABEL();
1355 return label_ids[nlabels++];
1358 static void readstmt(void)
1360 o_tmpdrop(-1);
1361 nts = 0;
1362 if (!tok_jmp('{')) {
1363 int _nlocals = nlocals;
1364 int _nglobals = nglobals;
1365 int _nenums = nenums;
1366 int _ntypedefs = ntypedefs;
1367 int _nstructs = nstructs;
1368 int _nfuncs = nfuncs;
1369 int _narrays = narrays;
1370 while (tok_jmp('}'))
1371 readstmt();
1372 nlocals = _nlocals;
1373 nenums = _nenums;
1374 ntypedefs = _ntypedefs;
1375 nstructs = _nstructs;
1376 nfuncs = _nfuncs;
1377 narrays = _narrays;
1378 nglobals = _nglobals;
1379 return;
1381 if (!readdefs(localdef, NULL)) {
1382 tok_expect(';');
1383 return;
1385 if (!tok_jmp(TOK_TYPEDEF)) {
1386 readdefs(typedefdef, NULL);
1387 tok_expect(';');
1388 return;
1390 if (!tok_jmp(TOK_IF)) {
1391 int l_fail = LABEL();
1392 int l_end = LABEL();
1393 tok_expect('(');
1394 readexpr();
1395 tok_expect(')');
1396 ts_pop_de(NULL);
1397 o_jz(l_fail);
1398 readstmt();
1399 if (!tok_jmp(TOK_ELSE)) {
1400 o_jmp(l_end);
1401 o_label(l_fail);
1402 readstmt();
1403 o_label(l_end);
1404 } else {
1405 o_label(l_fail);
1407 return;
1409 if (!tok_jmp(TOK_WHILE)) {
1410 int o_break = l_break;
1411 int o_cont = l_cont;
1412 l_break = LABEL();
1413 l_cont = LABEL();
1414 o_label(l_cont);
1415 tok_expect('(');
1416 readexpr();
1417 tok_expect(')');
1418 ts_pop_de(NULL);
1419 o_jz(l_break);
1420 readstmt();
1421 o_jmp(l_cont);
1422 o_label(l_break);
1423 l_break = o_break;
1424 l_cont = o_cont;
1425 return;
1427 if (!tok_jmp(TOK_DO)) {
1428 int o_break = l_break;
1429 int o_cont = l_cont;
1430 int l_beg = LABEL();
1431 l_break = LABEL();
1432 l_cont = LABEL();
1433 o_label(l_beg);
1434 readstmt();
1435 tok_expect(TOK_WHILE);
1436 tok_expect('(');
1437 o_label(l_cont);
1438 readexpr();
1439 ts_pop_de(NULL);
1440 o_jnz(l_beg);
1441 tok_expect(')');
1442 o_label(l_break);
1443 tok_expect(';');
1444 l_break = o_break;
1445 l_cont = o_cont;
1446 return;
1448 if (!tok_jmp(TOK_FOR)) {
1449 int o_break = l_break;
1450 int o_cont = l_cont;
1451 int l_check = LABEL(); /* for condition label */
1452 int l_body = LABEL(); /* for block label */
1453 l_cont = LABEL();
1454 l_break = LABEL();
1455 tok_expect('(');
1456 if (tok_see() != ';')
1457 readestmt();
1458 tok_expect(';');
1459 o_label(l_check);
1460 if (tok_see() != ';') {
1461 readestmt();
1462 ts_pop_de(NULL);
1463 o_jz(l_break);
1465 tok_expect(';');
1466 o_jmp(l_body);
1467 o_label(l_cont);
1468 if (tok_see() != ')')
1469 readestmt();
1470 tok_expect(')');
1471 o_jmp(l_check);
1472 o_label(l_body);
1473 readstmt();
1474 o_jmp(l_cont);
1475 o_label(l_break);
1476 l_break = o_break;
1477 l_cont = o_cont;
1478 return;
1480 if (!tok_jmp(TOK_SWITCH)) {
1481 readswitch();
1482 return;
1484 if (!tok_jmp(TOK_RETURN)) {
1485 int ret = tok_see() != ';';
1486 if (ret) {
1487 readexpr();
1488 ts_pop_de(NULL);
1490 tok_expect(';');
1491 o_ret(ret);
1492 return;
1494 if (!tok_jmp(TOK_BREAK)) {
1495 tok_expect(';');
1496 o_jmp(l_break);
1497 return;
1499 if (!tok_jmp(TOK_CONTINUE)) {
1500 tok_expect(';');
1501 o_jmp(l_cont);
1502 return;
1504 if (!tok_jmp(TOK_GOTO)) {
1505 tok_expect(TOK_NAME);
1506 o_jmp(label_id(tok_id()));
1507 tok_expect(';');
1508 return;
1510 readestmt();
1511 /* labels */
1512 if (!tok_jmp(':')) {
1513 o_label(label_id(tok_id()));
1514 return;
1516 tok_expect(';');
1519 static void readfunc(struct name *name, int flags)
1521 struct funcinfo *fi = &funcs[name->type.id];
1522 long beg = tok_addr();
1523 int i;
1524 strcpy(func_name, fi->name);
1525 o_func_beg(func_name, fi->nargs, F_GLOBAL(flags), fi->varg);
1526 for (i = 0; i < fi->nargs; i++) {
1527 struct name arg = {"", "", fi->args[i], o_arg2loc(i)};
1528 strcpy(arg.name, fi->argnames[i]);
1529 local_add(&arg);
1531 /* first pass: collecting statistics */
1532 label = 0;
1533 nlabels = 0;
1534 o_pass1();
1535 readstmt();
1536 tok_jump(beg);
1537 /* second pass: generating code */
1538 label = 0;
1539 nlabels = 0;
1540 o_pass2();
1541 readstmt();
1542 o_func_end();
1543 func_name[0] = '\0';
1544 nlocals = 0;
1547 static void readdecl(void)
1549 if (!tok_jmp(TOK_TYPEDEF)) {
1550 readdefs(typedefdef, NULL);
1551 tok_expect(';');
1552 return;
1554 readdefs_int(globaldef, NULL);
1555 tok_jmp(';');
1558 static void parse(void)
1560 while (tok_see() != TOK_EOF)
1561 readdecl();
1564 static void compat_macros(void)
1566 cpp_define("__STDC__", "");
1567 cpp_define("__linux__", "");
1568 cpp_define(I_ARCH, "");
1570 /* ignored keywords */
1571 cpp_define("const", "");
1572 cpp_define("register", "");
1573 cpp_define("volatile", "");
1574 cpp_define("inline", "");
1575 cpp_define("restrict", "");
1576 cpp_define("__inline__", "");
1577 cpp_define("__restrict__", "");
1578 cpp_define("__attribute__(x)", "");
1579 cpp_define("__builtin_va_list__", "long");
1582 int main(int argc, char *argv[])
1584 char obj[128] = "";
1585 int ofd;
1586 int i = 1;
1587 compat_macros();
1588 while (i < argc && argv[i][0] == '-') {
1589 if (argv[i][1] == 'I')
1590 cpp_addpath(argv[i][2] ? argv[i] + 2 : argv[++i]);
1591 if (argv[i][1] == 'D') {
1592 char *name = argv[i] + 2;
1593 char *def = "";
1594 char *eq = strchr(name, '=');
1595 if (eq) {
1596 *eq = '\0';
1597 def = eq + 1;
1599 cpp_define(name, def);
1601 if (argv[i][1] == 'o')
1602 strcpy(obj, argv[i][2] ? argv[i] + 2 : argv[++i]);
1603 i++;
1605 if (i == argc)
1606 die("neatcc: no file given\n");
1607 if (cpp_init(argv[i]))
1608 die("neatcc: cannot open <%s>\n", argv[i]);
1609 parse();
1610 if (!*obj) {
1611 strcpy(obj, argv[i]);
1612 obj[strlen(obj) - 1] = 'o';
1614 ofd = open(obj, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1615 o_write(ofd);
1616 close(ofd);
1617 return 0;
1621 /* parsing function and variable declarations */
1623 /* read the base type of a variable */
1624 static int basetype(struct type *type, unsigned *flags)
1626 int sign = 1;
1627 int size = 4;
1628 int done = 0;
1629 int i = 0;
1630 int isunion;
1631 char name[NAMELEN] = "";
1632 *flags = 0;
1633 type->flags = 0;
1634 type->ptr = 0;
1635 type->addr = 0;
1636 while (!done) {
1637 switch (tok_see()) {
1638 case TOK_STATIC:
1639 *flags |= F_STATIC;
1640 break;
1641 case TOK_EXTERN:
1642 *flags |= F_EXTERN;
1643 break;
1644 case TOK_VOID:
1645 sign = 0;
1646 size = 0;
1647 done = 1;
1648 break;
1649 case TOK_INT:
1650 done = 1;
1651 break;
1652 case TOK_CHAR:
1653 size = 1;
1654 done = 1;
1655 break;
1656 case TOK_SHORT:
1657 size = 2;
1658 break;
1659 case TOK_LONG:
1660 size = LONGSZ;
1661 break;
1662 case TOK_SIGNED:
1663 break;
1664 case TOK_UNSIGNED:
1665 sign = 0;
1666 break;
1667 case TOK_UNION:
1668 case TOK_STRUCT:
1669 isunion = tok_get() == TOK_UNION;
1670 if (!tok_jmp(TOK_NAME))
1671 strcpy(name, tok_id());
1672 if (tok_see() == '{')
1673 type->id = struct_create(name, isunion);
1674 else
1675 type->id = struct_find(name, isunion);
1676 type->flags |= T_STRUCT;
1677 type->bt = LONGSZ;
1678 return 0;
1679 case TOK_ENUM:
1680 tok_get();
1681 tok_jmp(TOK_NAME);
1682 if (tok_see() == '{')
1683 enum_create();
1684 type->bt = 4 | BT_SIGNED;
1685 return 0;
1686 default:
1687 if (tok_see() == TOK_NAME) {
1688 int id = typedef_find(tok_id());
1689 if (id != -1) {
1690 tok_get();
1691 memcpy(type, &typedefs[id].type,
1692 sizeof(*type));
1693 return 0;
1696 if (!i)
1697 return 1;
1698 done = 1;
1699 continue;
1701 i++;
1702 tok_get();
1704 type->bt = size | (sign ? BT_SIGNED : 0);
1705 return 0;
1708 static void readptrs(struct type *type)
1710 while (!tok_jmp('*')) {
1711 type->ptr++;
1712 if (!type->bt)
1713 type->bt = 1;
1717 /* read function arguments */
1718 static int readargs(struct type *args, char argnames[][NAMELEN], int *varg)
1720 int nargs = 0;
1721 tok_expect('(');
1722 *varg = 0;
1723 while (tok_see() != ')') {
1724 if (!tok_jmp(TOK3("..."))) {
1725 *varg = 1;
1726 break;
1728 if (readname(&args[nargs], argnames[nargs], NULL)) {
1729 /* argument has no type, assume int */
1730 tok_expect(TOK_NAME);
1731 memset(&args[nargs], 0, sizeof(struct type));
1732 args[nargs].bt = 4 | BT_SIGNED;
1733 strcpy(argnames[nargs], tok_id());
1735 /* argument arrays are pointers */
1736 array2ptr(&args[nargs]);
1737 nargs++;
1738 if (tok_jmp(','))
1739 break;
1741 tok_expect(')');
1742 /* void argument */
1743 if (nargs == 1 && !TYPE_BT(&args[0]))
1744 return 0;
1745 return nargs;
1748 /* read K&R function arguments */
1749 static void krdef(void *data, struct name *name, unsigned flags)
1751 struct funcinfo *fi = data;
1752 int i;
1753 for (i = 0; i < fi->nargs; i++)
1754 if (!strcmp(fi->argnames[i], name->name))
1755 memcpy(&fi->args[i], &name->type, sizeof(name->type));
1759 * readarrays() parses array specifiers when reading a definition in
1760 * readname(). The "type" parameter contains the type contained in the
1761 * inner array; for instance, type in "int *a[10][20]" would be an int
1762 * pointer. When returning, the "type" parameter is changed to point
1763 * to the final array. The function returns a pointer to the type in
1764 * the inner array; this is useful when the type is not complete yet,
1765 * like when creating an array of function pointers as in
1766 * "int (*f[10])(int)". If there is no array brackets, NULL is returned.
1768 static struct type *readarrays(struct type *type)
1770 long arsz[16];
1771 struct type *inner = NULL;
1772 int nar = 0;
1773 int i;
1774 while (!tok_jmp('[')) {
1775 long n = 0;
1776 if (tok_jmp(']')) {
1777 readexpr();
1778 ts_pop_de(NULL);
1779 if (o_popnum(&n))
1780 err("const expr expected\n");
1781 tok_expect(']');
1783 arsz[nar++] = n;
1785 for (i = nar - 1; i >= 0; i--) {
1786 type->id = array_add(type, arsz[i]);
1787 if (!inner)
1788 inner = &arrays[type->id].type;
1789 type->flags = T_ARRAY;
1790 type->bt = LONGSZ;
1791 type->ptr = 0;
1793 return inner;
1797 * readname() reads a variable definition; the name is copied into
1798 * "name" and the type is copied into "main" argument. The "base"
1799 * argument, if not NULL, indicates the base type of the variable.
1800 * For instance, the base type of "a" and "b" in "int *a, b[10]" is
1801 * "int". If NULL, basetype() is called directly to read the base
1802 * type of the variable. readname() returns zero, only if the
1803 * variable can be read.
1805 static int readname(struct type *main, char *name, struct type *base)
1807 struct type tpool[3];
1808 int npool = 0;
1809 struct type *type = &tpool[npool++];
1810 struct type *ptype = NULL; /* type inside parenthesis */
1811 struct type *btype = NULL; /* type before parenthesis */
1812 struct type *inner;
1813 unsigned flags;
1814 memset(tpool, 0, sizeof(tpool));
1815 if (name)
1816 *name = '\0';
1817 if (!base) {
1818 if (basetype(type, &flags))
1819 return 1;
1820 } else {
1821 memcpy(type, base, sizeof(*base));
1823 readptrs(type);
1824 if (!tok_jmp('(')) {
1825 btype = type;
1826 type = &tpool[npool++];
1827 ptype = type;
1828 readptrs(type);
1830 if (!tok_jmp(TOK_NAME) && name)
1831 strcpy(name, tok_id());
1832 inner = readarrays(type);
1833 if (ptype && inner)
1834 ptype = inner;
1835 if (ptype)
1836 tok_expect(')');
1837 if (tok_see() == '(') {
1838 struct type args[NARGS];
1839 char argnames[NARGS][NAMELEN];
1840 int varg = 0;
1841 int nargs = readargs(args, argnames, &varg);
1842 if (!ptype) {
1843 btype = type;
1844 type = &tpool[npool++];
1845 ptype = type;
1847 ptype->flags = T_FUNC;
1848 ptype->bt = LONGSZ;
1849 ptype->id = func_create(btype, name, argnames, args, nargs, varg);
1850 if (tok_see() != ';')
1851 while (tok_see() != '{' && !readdefs(krdef, &funcs[ptype->id]))
1852 tok_expect(';');
1853 } else {
1854 if (ptype && readarrays(type))
1855 array2ptr(type);
1857 memcpy(main, type, sizeof(*type));
1858 return 0;
1861 static int readtype(struct type *type)
1863 return readname(type, NULL, NULL);
1867 * readdef() reads a variable definitions statement. The definition
1868 * statement can appear in anywhere: global variables, function
1869 * local variables, struct fields, and typedefs. For each defined
1870 * variable, def() callback is called with the appropriate name
1871 * struct and flags; the callback should finish parsing the definition
1872 * by possibly reading the initializer expression and saving the name
1873 * struct.
1875 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
1876 void *data)
1878 struct type base;
1879 unsigned base_flags;
1880 if (basetype(&base, &base_flags))
1881 return 1;
1882 if (tok_see() == ';' || tok_see() == '{')
1883 return 0;
1884 do {
1885 struct name name = {{""}};
1886 if (readname(&name.type, name.name, &base))
1887 break;
1888 def(data, &name, base_flags);
1889 } while (!tok_jmp(','));
1890 return 0;
1893 /* just like readdefs, but default to int type; for handling K&R functions */
1894 static int readdefs_int(void (*def)(void *data, struct name *name, unsigned flags),
1895 void *data)
1897 struct type base;
1898 unsigned flags = 0;
1899 if (basetype(&base, &flags)) {
1900 if (tok_see() != TOK_NAME)
1901 return 1;
1902 memset(&base, 0, sizeof(base));
1903 base.bt = 4 | BT_SIGNED;
1905 if (tok_see() != ';') {
1906 do {
1907 struct name name = {{""}};
1908 if (readname(&name.type, name.name, &base))
1909 break;
1910 def(data, &name, flags);
1911 } while (!tok_jmp(','));
1913 return 0;
1917 /* parsing initializer expressions */
1919 static void jumpbrace(void)
1921 int depth = 0;
1922 while (tok_see() != '}' || depth--)
1923 if (tok_get() == '{')
1924 depth++;
1925 tok_expect('}');
1928 /* compute the size of the initializer expression */
1929 static int initsize(void)
1931 long addr = tok_addr();
1932 int n = 0;
1933 if (tok_jmp('='))
1934 return 0;
1935 if (!tok_jmp(TOK_STR)) {
1936 tok_str(NULL, &n);
1937 tok_jump(addr);
1938 return n;
1940 tok_expect('{');
1941 while (tok_jmp('}')) {
1942 long idx = n;
1943 if (!tok_jmp('[')) {
1944 readexpr();
1945 ts_pop_de(NULL);
1946 o_popnum(&idx);
1947 tok_expect(']');
1948 tok_expect('=');
1950 if (n < idx + 1)
1951 n = idx + 1;
1952 while (tok_see() != '}' && tok_see() != ',')
1953 if (tok_get() == '{')
1954 jumpbrace();
1955 tok_jmp(',');
1957 tok_jump(addr);
1958 return n;
1961 static struct type *innertype(struct type *t)
1963 if (t->flags & T_ARRAY && !t->ptr)
1964 return innertype(&arrays[t->id].type);
1965 return t;
1968 /* read the initializer expression and initialize basic types using set() cb */
1969 static void initexpr(struct type *t, int off, void *obj,
1970 void (*set)(void *obj, int off, struct type *t))
1972 if (tok_jmp('{')) {
1973 set(obj, off, t);
1974 return;
1976 if (!t->ptr && t->flags & T_STRUCT) {
1977 struct structinfo *si = &structs[t->id];
1978 int i;
1979 for (i = 0; i < si->nfields && tok_see() != '}'; i++) {
1980 struct name *field = &si->fields[i];
1981 if (!tok_jmp('.')) {
1982 tok_expect(TOK_NAME);
1983 field = struct_field(t->id, tok_id());
1984 tok_expect('=');
1986 initexpr(&field->type, off + field->addr, obj, set);
1987 if (tok_jmp(','))
1988 break;
1990 } else if (t->flags & T_ARRAY) {
1991 struct type *t_de = &arrays[t->id].type;
1992 int i;
1993 /* handling extra braces as in: char s[] = {"sth"} */
1994 if (TYPE_SZ(t_de) == 1 && tok_see() == TOK_STR) {
1995 set(obj, off, t);
1996 tok_expect('}');
1997 return;
1999 for (i = 0; tok_see() != '}'; i++) {
2000 long idx = i;
2001 struct type *it = t_de;
2002 if (!tok_jmp('[')) {
2003 readexpr();
2004 ts_pop_de(NULL);
2005 o_popnum(&idx);
2006 tok_expect(']');
2007 tok_expect('=');
2009 if (tok_see() != '{' && (tok_see() != TOK_STR ||
2010 !(it->flags & T_ARRAY)))
2011 it = innertype(t_de);
2012 initexpr(it, off + type_totsz(it) * idx, obj, set);
2013 if (tok_jmp(','))
2014 break;
2017 tok_expect('}');