ncc: fix handling function pointer types without a name
[neatcc.git] / ncc.c
bloba001ca1efad5339511f2eea0c80fd73fc9695e15
1 /*
2 * neatcc - a small and simple C compiler
4 * Copyright (C) 2010-2011 Ali Gholami Rudi
6 * This program is released under GNU GPL version 2.
7 */
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <stdio.h>
13 #include <sys/stat.h>
14 #include <sys/types.h>
15 #include "gen.h"
16 #include "tok.h"
17 #include "out.h"
19 static int nogen; /* don't generate code */
20 /* nogen macros */
21 #define o_bop(op) {if (!nogen) o_bop(op);}
22 #define o_uop(op) {if (!nogen) o_uop(op);}
23 #define o_cast(bt) {if (!nogen) o_cast(bt);}
24 #define o_memcpy() {if (!nogen) o_memcpy();}
25 #define o_memset() {if (!nogen) o_memset();}
26 #define o_call(argc, ret) {if (!nogen) o_call(argc, ret);}
27 #define o_ret(ret) {if (!nogen) o_ret(ret);}
28 #define o_assign(bt) {if (!nogen) o_assign(bt);}
29 #define o_deref(bt) {if (!nogen) o_deref(bt);}
30 #define o_load() {if (!nogen) o_load();}
31 #define o_popnum(c) (nogen ? 0 : o_popnum(c))
32 #define o_num(n) {if (!nogen) o_num(n);}
33 #define o_local(addr) {if (!nogen) o_local(addr);}
34 #define o_sym(sym) {if (!nogen) o_sym(sym);}
35 #define o_tmpdrop(n) {if (!nogen) o_tmpdrop(n);}
36 #define o_tmpswap() {if (!nogen) o_tmpswap();}
37 #define o_tmpcopy() {if (!nogen) o_tmpcopy();}
38 #define o_label(id) {if (!nogen) o_label(id);}
39 #define o_jz(id) {if (!nogen) o_jz(id);}
40 #define o_jnz(id) {if (!nogen) o_jnz(id);}
41 #define o_jmp(id) {if (!nogen) o_jmp(id);}
42 #define o_fork() {if (!nogen) o_fork();}
43 #define o_forkpush() {if (!nogen) o_forkpush();}
44 #define o_forkjoin() {if (!nogen) o_forkjoin();}
46 #define MAXLOCALS (1 << 10)
47 #define MAXGLOBALS (1 << 10)
48 #define MAXARGS (1 << 5)
50 #define ALIGN(x, a) (((x) + (a) - 1) & ~((a) - 1))
51 #define MIN(a, b) ((a) < (b) ? (a) : (b))
53 #define TYPE_BT(t) ((t)->ptr ? LONGSZ : (t)->bt)
54 #define TYPE_SZ(t) ((t)->ptr ? LONGSZ : (t)->bt & BT_SZMASK)
56 /* type->flag values */
57 #define T_ARRAY 0x01
58 #define T_STRUCT 0x02
59 #define T_FUNC 0x04
61 /* variable definition flags */
62 #define F_STATIC 0x01
63 #define F_EXTERN 0x02
65 struct type {
66 unsigned bt;
67 unsigned flags;
68 int ptr;
69 int id; /* for structs, functions and arrays */
70 int addr; /* the address is passed to gen.c; deref for value */
73 /* type stack */
74 static struct type ts[MAXTMP];
75 static int nts;
77 static void ts_push_bt(unsigned bt)
79 ts[nts].ptr = 0;
80 ts[nts].flags = 0;
81 ts[nts].addr = 0;
82 ts[nts++].bt = bt;
85 static void ts_push(struct type *t)
87 struct type *d = &ts[nts++];
88 memcpy(d, t, sizeof(*t));
91 static void ts_push_addr(struct type *t)
93 ts_push(t);
94 ts[nts - 1].addr = 1;
97 static void ts_pop(struct type *type)
99 nts--;
100 if (type)
101 *type = ts[nts];
104 void err(char *msg)
106 die("%s: %s", cpp_loc(tok_addr()), msg);
109 struct name {
110 char name[NAMELEN];
111 char elfname[NAMELEN]; /* local elf name for static variables in function */
112 struct type type;
113 long addr; /* local stack offset, global data addr, struct offset */
116 static struct name locals[MAXLOCALS];
117 static int nlocals;
118 static struct name globals[MAXGLOBALS];
119 static int nglobals;
121 static void local_add(struct name *name)
123 if (nlocals >= MAXLOCALS)
124 err("nomem: MAXLOCALS reached!\n");
125 memcpy(&locals[nlocals++], name, sizeof(*name));
128 static int local_find(char *name)
130 int i;
131 for (i = nlocals - 1; i >= 0; --i)
132 if (!strcmp(locals[i].name, name))
133 return i;
134 return -1;
137 static int global_find(char *name)
139 int i;
140 for (i = nglobals - 1; i >= 0; i--)
141 if (!strcmp(name, globals[i].name))
142 return i;
143 return -1;
146 static void global_add(struct name *name)
148 if (nglobals >= MAXGLOBALS)
149 err("nomem: MAXGLOBALS reached!\n");
150 memcpy(&globals[nglobals++], name, sizeof(*name));
153 #define LABEL() (++label)
155 static int label; /* last used label id */
156 static int l_break; /* current break label */
157 static int l_cont; /* current continue label */
159 #define MAXENUMS (1 << 10)
161 static struct enumval {
162 char name[NAMELEN];
163 int n;
164 } enums[MAXENUMS];
165 static int nenums;
167 static void enum_add(char *name, int val)
169 struct enumval *ev = &enums[nenums++];
170 if (nenums >= MAXENUMS)
171 err("nomem: MAXENUMS reached!\n");
172 strcpy(ev->name, name);
173 ev->n = val;
176 static int enum_find(int *val, char *name)
178 int i;
179 for (i = nenums - 1; i >= 0; --i)
180 if (!strcmp(name, enums[i].name)) {
181 *val = enums[i].n;
182 return 0;
184 return 1;
187 #define MAXTYPEDEFS (1 << 10)
189 static struct typdefinfo {
190 char name[NAMELEN];
191 struct type type;
192 } typedefs[MAXTYPEDEFS];
193 static int ntypedefs;
195 static void typedef_add(char *name, struct type *type)
197 struct typdefinfo *ti = &typedefs[ntypedefs++];
198 if (ntypedefs >= MAXTYPEDEFS)
199 err("nomem: MAXTYPEDEFS reached!\n");
200 strcpy(ti->name, name);
201 memcpy(&ti->type, type, sizeof(*type));
204 static int typedef_find(char *name)
206 int i;
207 for (i = ntypedefs - 1; i >= 0; --i)
208 if (!strcmp(name, typedefs[i].name))
209 return i;
210 return -1;
213 #define MAXARRAYS (1 << 10)
215 static struct array {
216 struct type type;
217 int n;
218 } arrays[MAXARRAYS];
219 static int narrays;
221 static int array_add(struct type *type, int n)
223 struct array *a = &arrays[narrays++];
224 if (narrays >= MAXARRAYS)
225 err("nomem: MAXARRAYS reached!\n");
226 memcpy(&a->type, type, sizeof(*type));
227 a->n = n;
228 return a - arrays;
231 static void array2ptr(struct type *t)
233 if (t->flags & T_ARRAY && !t->ptr) {
234 memcpy(t, &arrays[t->id].type, sizeof(*t));
235 t->ptr++;
239 #define MAXSTRUCTS (1 << 10)
240 #define MAXFIELDS (1 << 7)
242 static struct structinfo {
243 char name[NAMELEN];
244 struct name fields[MAXFIELDS];
245 int nfields;
246 int isunion;
247 int size;
248 } structs[MAXSTRUCTS];
249 static int nstructs;
251 static int struct_find(char *name, int isunion)
253 int i;
254 for (i = nstructs - 1; i >= 0; --i)
255 if (*structs[i].name && !strcmp(name, structs[i].name) &&
256 structs[i].isunion == isunion)
257 return i;
258 i = nstructs++;
259 if (nstructs >= MAXSTRUCTS)
260 err("nomem: MAXTYPES reached!\n");
261 memset(&structs[i], 0, sizeof(structs[i]));
262 strcpy(structs[i].name, name);
263 structs[i].isunion = isunion;
264 return i;
267 static struct name *struct_field(int id, char *name)
269 struct structinfo *si = &structs[id];
270 int i;
271 for (i = 0; i < si->nfields; i++)
272 if (!strcmp(name, si->fields[i].name))
273 return &si->fields[i];
274 err("field not found\n");
277 /* return t's size */
278 static int type_totsz(struct type *t)
280 if (t->ptr)
281 return LONGSZ;
282 if (t->flags & T_ARRAY)
283 return arrays[t->id].n * type_totsz(&arrays[t->id].type);
284 return t->flags & T_STRUCT ? structs[t->id].size : BT_SZ(t->bt);
287 /* return t's dereferenced size */
288 static unsigned type_szde(struct type *t)
290 struct type de = *t;
291 array2ptr(&de);
292 de.ptr--;
293 return type_totsz(&de);
296 /* dereference stack top if t->addr (ie. address is pushed to gen.c) */
297 static void ts_de(int deref)
299 struct type *t = &ts[nts - 1];
300 array2ptr(t);
301 if (deref && t->addr && (t->ptr || !(t->flags & T_FUNC)))
302 o_deref(TYPE_BT(t));
303 t->addr = 0;
306 /* pop stack pop to *t and dereference if t->addr */
307 static void ts_pop_de(struct type *t)
309 ts_de(1);
310 ts_pop(t);
313 /* pop the top 2 stack values and dereference them if t->addr */
314 static void ts_pop_de2(struct type *t1, struct type *t2)
316 ts_pop_de(t1);
317 o_tmpswap();
318 ts_pop_de(t2);
319 o_tmpswap();
322 static int tok_jmp(int tok)
324 if (tok_see() != tok)
325 return 1;
326 tok_get();
327 return 0;
330 static void tok_expect(int tok)
332 if (tok_get() != tok)
333 err("syntax error\n");
336 static unsigned bt_op(unsigned bt1, unsigned bt2)
338 unsigned s1 = BT_SZ(bt1);
339 unsigned s2 = BT_SZ(bt2);
340 return (bt1 | bt2) & BT_SIGNED | (s1 > s2 ? s1 : s2);
343 static void ts_binop(int op)
345 struct type t1, t2;
346 int bt;
347 ts_pop_de2(&t1, &t2);
348 if (op == O_DIV || op == O_MOD)
349 bt = TYPE_BT(&t2);
350 else
351 bt = bt_op(TYPE_BT(&t1), TYPE_BT(&t2));
352 o_bop(op | (bt & BT_SIGNED ? O_SIGNED : 0));
353 ts_push_bt(bt);
356 static void ts_addop(int op)
358 struct type t1, t2;
359 ts_pop_de2(&t1, &t2);
360 if (!t1.ptr && !t2.ptr) {
361 o_bop(op);
362 ts_push_bt(bt_op(TYPE_BT(&t1), TYPE_BT(&t2)));
363 return;
365 if (t1.ptr && !t2.ptr)
366 o_tmpswap();
367 if (!t1.ptr && t2.ptr)
368 if (type_szde(&t2) > 1) {
369 o_num(type_szde(&t2));
370 o_bop(O_MUL);
372 if (t1.ptr && !t2.ptr)
373 o_tmpswap();
374 o_bop(op);
375 if (t1.ptr && t2.ptr) {
376 int sz = type_szde(&t1);
377 if (sz > 1) {
378 o_num(sz);
379 o_bop(O_DIV);
381 ts_push_bt(4 | BT_SIGNED);
382 } else {
383 ts_push(t1.ptr ? &t1 : &t2);
387 /* function prototypes for parsing function and variable declarations */
388 static int readname(struct type *main, char *name, struct type *base);
389 static int readtype(struct type *type);
390 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
391 void *data);
392 static int readdefs_int(void (*def)(void *data, struct name *name, unsigned flags),
393 void *data);
395 /* function prototypes for parsing initializer expressions */
396 static int initsize(void);
397 static void initexpr(struct type *t, int off, void *obj,
398 void (*set)(void *obj, int off, struct type *t));
400 static int type_alignment(struct type *t)
402 if (t->flags & T_ARRAY && !t->ptr)
403 return type_alignment(&arrays[t->id].type);
404 if (t->flags & T_STRUCT && !t->ptr)
405 return type_alignment(&structs[t->id].fields[0].type);
406 return MIN(LONGSZ, type_totsz(t));
409 static void structdef(void *data, struct name *name, unsigned flags)
411 struct structinfo *si = data;
412 if (si->isunion) {
413 name->addr = 0;
414 if (si->size < type_totsz(&name->type))
415 si->size = type_totsz(&name->type);
416 } else {
417 struct type *t = &name->type;
418 int alignment = type_alignment(t);
419 if (t->flags & T_ARRAY && !t->ptr)
420 alignment = MIN(LONGSZ, type_totsz(&arrays[t->id].type));
421 si->size = ALIGN(si->size, alignment);
422 name->addr = si->size;
423 si->size += type_totsz(&name->type);
425 memcpy(&si->fields[si->nfields++], name, sizeof(*name));
428 static int struct_create(char *name, int isunion)
430 int id = struct_find(name, isunion);
431 struct structinfo *si = &structs[id];
432 tok_expect('{');
433 while (tok_jmp('}')) {
434 readdefs(structdef, si);
435 tok_expect(';');
437 return id;
440 static void readexpr(void);
442 static void enum_create(void)
444 long n = 0;
445 tok_expect('{');
446 while (tok_jmp('}')) {
447 char name[NAMELEN];
448 tok_expect(TOK_NAME);
449 strcpy(name, tok_id());
450 if (!tok_jmp('=')) {
451 readexpr();
452 ts_pop_de(NULL);
453 if (o_popnum(&n))
454 err("const expr expected!\n");
456 enum_add(name, n++);
457 tok_jmp(',');
461 /* used to differenciate labels from case and cond exprs */
462 static int ncexpr;
463 static int caseexpr;
465 static void readpre(void);
467 static char *tmp_str(char *buf, int len)
469 static char name[NAMELEN];
470 static int id;
471 void *dat;
472 sprintf(name, "__neatcc.s%d", id++);
473 dat = o_mkdat(name, len, 0);
474 memcpy(dat, buf, len);
475 return name;
478 static void readprimary(void)
480 if (!tok_jmp(TOK_NUM)) {
481 long n;
482 int bt = tok_num(&n);
483 ts_push_bt(bt);
484 o_num(n);
485 return;
487 if (!tok_jmp(TOK_STR)) {
488 struct type t;
489 char buf[BUFSIZE];
490 int len;
491 t.bt = 1 | BT_SIGNED;
492 t.ptr = 1;
493 t.addr = 0;
494 t.flags = 0;
495 ts_push(&t);
496 len = tok_str(buf);
497 o_sym(tmp_str(buf, len));
498 return;
500 if (!tok_jmp(TOK_NAME)) {
501 struct name unkn = {""};
502 char *name = unkn.name;
503 int n;
504 strcpy(name, tok_id());
505 /* don't search for labels here */
506 if (!ncexpr && !caseexpr && tok_see() == ':')
507 return;
508 if ((n = local_find(name)) != -1) {
509 struct name *l = &locals[n];
510 o_local(l->addr);
511 ts_push_addr(&l->type);
512 return;
514 if ((n = global_find(name)) != -1) {
515 struct name *g = &globals[n];
516 o_sym(*g->elfname ? g->elfname : g->name);
517 ts_push_addr(&g->type);
518 return;
520 if (!enum_find(&n, name)) {
521 ts_push_bt(4 | BT_SIGNED);
522 o_num(n);
523 return;
525 if (tok_see() != '(')
526 err("unknown symbol\n");
527 global_add(&unkn);
528 ts_push_bt(LONGSZ);
529 o_sym(unkn.name);
530 return;
532 if (!tok_jmp('(')) {
533 struct type t;
534 if (!readtype(&t)) {
535 struct type o;
536 tok_expect(')');
537 readpre();
538 ts_pop_de(&o);
539 ts_push(&t);
540 if (!t.ptr || !o.ptr)
541 o_cast(TYPE_BT(&t));
542 } else {
543 readexpr();
544 while (tok_jmp(')')) {
545 tok_expect(',');
546 ts_pop(NULL);
547 o_tmpdrop(1);
548 readexpr();
551 return;
555 static void arrayderef(void)
557 struct type t;
558 int sz;
559 ts_pop_de(NULL);
560 ts_pop(&t);
561 if (!(t.flags & T_ARRAY && !t.ptr) && t.addr) {
562 o_tmpswap();
563 o_deref(TYPE_BT(&t));
564 o_tmpswap();
566 array2ptr(&t);
567 t.ptr--;
568 sz = type_totsz(&t);
569 t.addr = 1;
570 if (sz > 1) {
571 o_num(sz);
572 o_bop(O_MUL);
574 o_bop(O_ADD);
575 ts_push(&t);
578 static void inc_post(int op)
580 struct type t = ts[nts - 1];
581 /* pushing the value before inc */
582 o_tmpcopy();
583 ts_de(1);
584 o_load();
585 o_tmpswap();
587 /* increment by 1 or pointer size */
588 o_tmpcopy();
589 ts_push(&t);
590 ts_pop_de(&t);
591 o_num(t.ptr > 0 ? type_szde(&t) : 1);
592 o_bop(op);
594 /* assign back */
595 o_assign(TYPE_BT(&t));
596 o_tmpdrop(1);
599 static void readfield(void)
601 struct name *field;
602 struct type t;
603 tok_expect(TOK_NAME);
604 ts_pop(&t);
605 array2ptr(&t);
606 field = struct_field(t.id, tok_id());
607 if (field->addr) {
608 o_num(field->addr);
609 o_bop(O_ADD);
611 ts_push_addr(&field->type);
614 #define MAXFUNCS (1 << 10)
616 static struct funcinfo {
617 struct type args[MAXARGS];
618 struct type ret;
619 int nargs;
620 int varg;
621 /* function and argument names; useful only when defining */
622 char argnames[MAXARGS][NAMELEN];
623 char name[NAMELEN];
624 } funcs[MAXFUNCS];
625 static int nfuncs;
627 static int func_create(struct type *ret, char *name, char argnames[][NAMELEN],
628 struct type *args, int nargs, int varg)
630 struct funcinfo *fi = &funcs[nfuncs++];
631 int i;
632 if (nfuncs >= MAXFUNCS)
633 err("nomem: MAXFUNCS reached!\n");
634 memcpy(&fi->ret, ret, sizeof(*ret));
635 for (i = 0; i < nargs; i++)
636 memcpy(&fi->args[i], &args[i], sizeof(*ret));
637 fi->nargs = nargs;
638 fi->varg = varg;
639 strcpy(fi->name, name ? name : "");
640 for (i = 0; i < nargs; i++)
641 strcpy(fi->argnames[i], argnames[i]);
642 return fi - funcs;
645 static void readcall(void)
647 struct type t;
648 struct funcinfo *fi;
649 int argc = 0;
650 ts_pop(&t);
651 if (t.flags & T_FUNC && t.ptr > 0)
652 o_deref(LONGSZ);
653 fi = t.flags & T_FUNC ? &funcs[t.id] : NULL;
654 if (tok_see() != ')') {
655 do {
656 readexpr();
657 ts_pop_de(NULL);
658 argc++;
659 } while (!tok_jmp(','));
661 tok_expect(')');
662 o_call(argc, fi ? TYPE_BT(&fi->ret) : 4 | BT_SIGNED);
663 if (fi) {
664 if (TYPE_BT(&fi->ret))
665 o_cast(TYPE_BT(&fi->ret));
666 ts_push(&fi->ret);
667 } else {
668 ts_push_bt(4 | BT_SIGNED);
672 static void readpost(void)
674 readprimary();
675 while (1) {
676 if (!tok_jmp('[')) {
677 readexpr();
678 tok_expect(']');
679 arrayderef();
680 continue;
682 if (!tok_jmp('(')) {
683 readcall();
684 continue;
686 if (!tok_jmp(TOK2("++"))) {
687 inc_post(O_ADD);
688 continue;
690 if (!tok_jmp(TOK2("--"))) {
691 inc_post(O_SUB);
692 continue;
694 if (!tok_jmp('.')) {
695 readfield();
696 continue;
698 if (!tok_jmp(TOK2("->"))) {
699 ts_de(1);
700 readfield();
701 continue;
703 break;
707 static void inc_pre(int op)
709 struct type t;
710 readpre();
711 /* copy the destination */
712 o_tmpcopy();
713 ts_push(&ts[nts - 1]);
714 /* increment by 1 or pointer size */
715 ts_pop_de(&t);
716 o_num(t.ptr > 0 ? type_szde(&t) : 1);
717 o_bop(op);
718 /* assign the result */
719 o_assign(TYPE_BT(&t));
720 ts_de(0);
723 static void readpre(void)
725 if (!tok_jmp('&')) {
726 struct type type;
727 readpre();
728 ts_pop(&type);
729 if (!type.addr)
730 err("cannot use the address\n");
731 type.ptr++;
732 type.addr = 0;
733 ts_push(&type);
734 return;
736 if (!tok_jmp('*')) {
737 struct type t;
738 readpre();
739 ts_pop(&t);
740 array2ptr(&t);
741 if (!t.ptr)
742 err("dereferencing non-pointer\n");
743 if (t.addr)
744 o_deref(TYPE_BT(&t));
745 t.ptr--;
746 t.addr = 1;
747 ts_push(&t);
748 return;
750 if (!tok_jmp('!')) {
751 readpre();
752 ts_pop_de(NULL);
753 o_uop(O_LNOT);
754 ts_push_bt(4 | BT_SIGNED);
755 return;
757 if (!tok_jmp('-')) {
758 readpre();
759 ts_de(1);
760 o_uop(O_NEG);
761 return;
763 if (!tok_jmp('~')) {
764 readpre();
765 ts_de(1);
766 o_uop(O_NOT);
767 return;
769 if (!tok_jmp(TOK2("++"))) {
770 inc_pre(O_ADD);
771 return;
773 if (!tok_jmp(TOK2("--"))) {
774 inc_pre(O_SUB);
775 return;
777 if (!tok_jmp(TOK_SIZEOF)) {
778 struct type t;
779 int op = !tok_jmp('(');
780 if (readtype(&t)) {
781 nogen++;
782 if (op)
783 readexpr();
784 else
785 readpre();
786 nogen--;
787 ts_pop(&t);
789 ts_push_bt(4);
790 o_num(type_totsz(&t));
791 if (op)
792 tok_expect(')');
793 return;
795 readpost();
798 static void readmul(void)
800 readpre();
801 while (1) {
802 if (!tok_jmp('*')) {
803 readpre();
804 ts_binop(O_MUL);
805 continue;
807 if (!tok_jmp('/')) {
808 readpre();
809 ts_binop(O_DIV);
810 continue;
812 if (!tok_jmp('%')) {
813 readpre();
814 ts_binop(O_MOD);
815 continue;
817 break;
821 static void readadd(void)
823 readmul();
824 while (1) {
825 if (!tok_jmp('+')) {
826 readmul();
827 ts_addop(O_ADD);
828 continue;
830 if (!tok_jmp('-')) {
831 readmul();
832 ts_addop(O_SUB);
833 continue;
835 break;
839 static void shift(int op)
841 struct type t;
842 readadd();
843 ts_pop_de2(NULL, &t);
844 o_bop(op | (BT_SIGNED & TYPE_BT(&t) ? O_SIGNED : 0));
845 ts_push_bt(TYPE_BT(&t));
848 static void readshift(void)
850 readadd();
851 while (1) {
852 if (!tok_jmp(TOK2("<<"))) {
853 shift(O_SHL);
854 continue;
856 if (!tok_jmp(TOK2(">>"))) {
857 shift(O_SHR);
858 continue;
860 break;
864 static void cmp(int op)
866 struct type t1, t2;
867 int bt;
868 readshift();
869 ts_pop_de2(&t1, &t2);
870 bt = bt_op(TYPE_BT(&t1), TYPE_BT(&t2));
871 o_bop(op | (bt & BT_SIGNED ? O_SIGNED : 0));
872 ts_push_bt(4 | BT_SIGNED);
875 static void readcmp(void)
877 readshift();
878 while (1) {
879 if (!tok_jmp('<')) {
880 cmp(O_LT);
881 continue;
883 if (!tok_jmp('>')) {
884 cmp(O_GT);
885 continue;
887 if (!tok_jmp(TOK2("<="))) {
888 cmp(O_LE);
889 continue;
891 if (!tok_jmp(TOK2(">="))) {
892 cmp(O_GE);
893 continue;
895 break;
899 static void eq(int op)
901 readcmp();
902 ts_pop_de2(NULL, NULL);
903 o_bop(op);
904 ts_push_bt(4 | BT_SIGNED);
907 static void readeq(void)
909 readcmp();
910 while (1) {
911 if (!tok_jmp(TOK2("=="))) {
912 eq(O_EQ);
913 continue;
915 if (!tok_jmp(TOK2("!="))) {
916 eq(O_NEQ);
917 continue;
919 break;
923 static void readbitand(void)
925 readeq();
926 while (!tok_jmp('&')) {
927 readeq();
928 ts_binop(O_AND);
932 static void readxor(void)
934 readbitand();
935 while (!tok_jmp('^')) {
936 readbitand();
937 ts_binop(O_XOR);
941 static void readbitor(void)
943 readxor();
944 while (!tok_jmp('|')) {
945 readxor();
946 ts_binop(O_OR);
950 #define MAXCOND (1 << 7)
952 static void readand(void)
954 int l_out = LABEL();
955 int l_fail = LABEL();
956 readbitor();
957 if (tok_see() != TOK2("&&"))
958 return;
959 o_fork();
960 ts_pop_de(NULL);
961 o_jz(l_fail);
962 while (!tok_jmp(TOK2("&&"))) {
963 readbitor();
964 ts_pop_de(NULL);
965 o_jz(l_fail);
967 o_num(1);
968 o_forkpush();
969 o_jmp(l_out);
970 o_label(l_fail);
971 o_num(0);
972 o_forkpush();
973 o_forkjoin();
974 o_label(l_out);
975 ts_push_bt(4 | BT_SIGNED);
978 static void reador(void)
980 int l_pass = LABEL();
981 int l_end = LABEL();
982 readand();
983 if (tok_see() != TOK2("||"))
984 return;
985 o_fork();
986 ts_pop_de(NULL);
987 o_jnz(l_pass);
988 while (!tok_jmp(TOK2("||"))) {
989 readand();
990 ts_pop_de(NULL);
991 o_jnz(l_pass);
993 o_num(0);
994 o_forkpush();
995 o_jmp(l_end);
996 o_label(l_pass);
997 o_num(1);
998 o_forkpush();
999 o_forkjoin();
1000 o_label(l_end);
1001 ts_push_bt(4 | BT_SIGNED);
1004 static void readcexpr(void);
1006 static int readcexpr_const(void)
1008 long c;
1009 if (o_popnum(&c))
1010 return -1;
1011 if (!c)
1012 nogen++;
1013 readcexpr();
1014 /* both branches yield the same type; so ignore the first */
1015 ts_pop_de(NULL);
1016 tok_expect(':');
1017 if (c)
1018 nogen++;
1019 else
1020 nogen--;
1021 readcexpr();
1022 /* making sure t->addr == 0 on both branches */
1023 ts_de(1);
1024 if (c)
1025 nogen--;
1026 return 0;
1029 static void readcexpr(void)
1031 reador();
1032 if (tok_jmp('?'))
1033 return;
1034 ncexpr++;
1035 ts_pop_de(NULL);
1036 o_fork();
1037 if (readcexpr_const()) {
1038 int l_fail = LABEL();
1039 int l_end = LABEL();
1040 o_jz(l_fail);
1041 readcexpr();
1042 /* both branches yield the same type; so ignore the first */
1043 ts_pop_de(NULL);
1044 o_forkpush();
1045 o_jmp(l_end);
1047 tok_expect(':');
1048 o_label(l_fail);
1049 readcexpr();
1050 /* making sure t->addr == 0 on both branches */
1051 ts_de(1);
1052 o_forkpush();
1053 o_forkjoin();
1054 o_label(l_end);
1056 ncexpr--;
1059 static void opassign(int op, int ptrop)
1061 struct type t = ts[nts - 1];
1062 o_tmpcopy();
1063 ts_push(&t);
1064 readexpr();
1065 ts_addop(op);
1066 o_assign(TYPE_BT(&ts[nts - 2]));
1067 ts_pop(NULL);
1068 ts_de(0);
1071 static void doassign(void)
1073 struct type t = ts[nts - 1];
1074 if (!t.ptr && t.flags & T_STRUCT) {
1075 ts_pop(NULL);
1076 o_num(type_totsz(&t));
1077 o_memcpy();
1078 } else {
1079 ts_pop_de(NULL);
1080 o_assign(TYPE_BT(&ts[nts - 1]));
1081 ts_de(0);
1085 static void readexpr(void)
1087 readcexpr();
1088 if (!tok_jmp('=')) {
1089 readexpr();
1090 doassign();
1091 return;
1093 if (!tok_jmp(TOK2("+="))) {
1094 opassign(O_ADD, 1);
1095 return;
1097 if (!tok_jmp(TOK2("-="))) {
1098 opassign(O_SUB, 1);
1099 return;
1101 if (!tok_jmp(TOK2("*="))) {
1102 opassign(O_MUL, 0);
1103 return;
1105 if (!tok_jmp(TOK2("/="))) {
1106 opassign(O_DIV, 0);
1107 return;
1109 if (!tok_jmp(TOK2("%="))) {
1110 opassign(O_MOD, 0);
1111 return;
1113 if (!tok_jmp(TOK3("<<="))) {
1114 opassign(O_SHL, 0);
1115 return;
1117 if (!tok_jmp(TOK3(">>="))) {
1118 opassign(O_SHR, 0);
1119 return;
1121 if (!tok_jmp(TOK3("&="))) {
1122 opassign(O_AND, 0);
1123 return;
1125 if (!tok_jmp(TOK3("|="))) {
1126 opassign(O_OR, 0);
1127 return;
1129 if (!tok_jmp(TOK3("^="))) {
1130 opassign(O_XOR, 0);
1131 return;
1135 static void readestmt(void)
1137 do {
1138 o_tmpdrop(-1);
1139 nts = 0;
1140 readexpr();
1141 } while (!tok_jmp(','));
1144 #define F_GLOBAL(flags) (!((flags) & F_STATIC))
1146 static void globalinit(void *obj, int off, struct type *t)
1148 struct name *name = obj;
1149 char *elfname = *name->elfname ? name->elfname : name->name;
1150 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1151 struct type *t_de = &arrays[t->id].type;
1152 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1153 char buf[BUFSIZE];
1154 int len;
1155 tok_expect(TOK_STR);
1156 len = tok_str(buf);
1157 memcpy((void *) name->addr + off, buf, len);
1158 return;
1161 readexpr();
1162 o_datset(elfname, off, TYPE_BT(t));
1163 ts_pop(NULL);
1166 static void readfunc(struct name *name, int flags);
1168 static void globaldef(void *data, struct name *name, unsigned flags)
1170 struct type *t = &name->type;
1171 char *elfname = *name->elfname ? name->elfname : name->name;
1172 int sz;
1173 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1174 if (~flags & F_EXTERN)
1175 arrays[t->id].n = initsize();
1176 sz = type_totsz(t);
1177 if (!(flags & F_EXTERN) && (!(t->flags & T_FUNC) || t->ptr)) {
1178 if (tok_see() == '=')
1179 name->addr = (long) o_mkdat(elfname, sz, F_GLOBAL(flags));
1180 else
1181 o_mkbss(elfname, sz, F_GLOBAL(flags));
1183 global_add(name);
1184 if (!tok_jmp('='))
1185 initexpr(t, 0, name, globalinit);
1186 if (tok_see() == '{' && name->type.flags & T_FUNC)
1187 readfunc(name, flags);
1190 /* generate the address of local + off */
1191 static void o_localoff(long addr, int off)
1193 o_local(addr);
1194 if (off) {
1195 o_num(off);
1196 o_bop(O_ADD);
1200 static void localinit(void *obj, int off, struct type *t)
1202 long addr = *(long *) obj;
1203 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1204 struct type *t_de = &arrays[t->id].type;
1205 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1206 char buf[BUFSIZE];
1207 int len;
1208 tok_expect(TOK_STR);
1209 len = tok_str(buf);
1210 o_localoff(addr, off);
1211 o_sym(tmp_str(buf, len));
1212 o_num(len);
1213 o_memcpy();
1214 o_tmpdrop(1);
1215 return;
1218 o_localoff(addr, off);
1219 ts_push(t);
1220 readexpr();
1221 doassign();
1222 ts_pop(NULL);
1223 o_tmpdrop(1);
1226 /* current function name */
1227 static char func_name[NAMELEN];
1229 static void localdef(void *data, struct name *name, unsigned flags)
1231 struct type *t = &name->type;
1232 if ((flags & F_EXTERN) || (t->flags & T_FUNC) && !t->ptr) {
1233 global_add(name);
1234 return;
1236 if (flags & F_STATIC) {
1237 sprintf(name->elfname, "__neatcc.%s.%s", func_name, name->name);
1238 globaldef(data, name, flags);
1239 return;
1241 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1242 arrays[t->id].n = initsize();
1243 name->addr = o_mklocal(type_totsz(&name->type));
1244 local_add(name);
1245 if (!tok_jmp('=')) {
1246 if (t->flags & (T_ARRAY | T_STRUCT) && !t->ptr) {
1247 o_local(name->addr);
1248 o_num(0);
1249 o_num(type_totsz(t));
1250 o_memset();
1251 o_tmpdrop(1);
1253 initexpr(t, 0, &name->addr, localinit);
1257 static void typedefdef(void *data, struct name *name, unsigned flags)
1259 typedef_add(name->name, &name->type);
1262 static void readstmt(void);
1264 #define MAXCASES (1 << 7)
1266 static void readswitch(void)
1268 int o_break = l_break;
1269 long val_addr = o_mklocal(LONGSZ);
1270 struct type t;
1271 int ncases = 0; /* number of case labels */
1272 int l_failed = LABEL(); /* address of last failed jmp */
1273 int l_matched = LABEL(); /* address of last walk through jmp */
1274 int l_default = 0; /* default case label */
1275 l_break = LABEL();
1276 tok_expect('(');
1277 readexpr();
1278 ts_pop_de(&t);
1279 o_local(val_addr);
1280 o_tmpswap();
1281 o_assign(TYPE_BT(&t));
1282 ts_de(0);
1283 o_tmpdrop(1);
1284 tok_expect(')');
1285 tok_expect('{');
1286 while (tok_jmp('}')) {
1287 if (tok_see() != TOK_CASE && tok_see() != TOK_DEFAULT) {
1288 readstmt();
1289 continue;
1291 if (ncases)
1292 o_jmp(l_matched);
1293 if (tok_get() == TOK_CASE) {
1294 o_label(l_failed);
1295 l_failed = LABEL();
1296 caseexpr = 1;
1297 readexpr();
1298 ts_pop_de(NULL);
1299 caseexpr = 0;
1300 o_local(val_addr);
1301 o_deref(TYPE_BT(&t));
1302 o_bop(O_EQ);
1303 o_jz(l_failed);
1304 o_tmpdrop(1);
1305 } else {
1306 if (!ncases)
1307 o_jmp(l_failed);
1308 l_default = LABEL();
1309 o_label(l_default);
1311 tok_expect(':');
1312 o_label(l_matched);
1313 l_matched = LABEL();
1314 ncases++;
1316 o_rmlocal(val_addr, LONGSZ);
1317 o_jmp(l_break);
1318 o_label(l_failed);
1319 if (l_default)
1320 o_jmp(l_default);
1321 o_label(l_break);
1322 l_break = o_break;
1325 #define MAXLABELS (1 << 10)
1327 static char label_name[MAXLABELS][NAMELEN];
1328 static int label_ids[MAXLABELS];
1329 static int nlabels;
1331 static int label_id(char *name)
1333 int i;
1334 for (i = nlabels - 1; i >= 0; --i)
1335 if (!strcmp(label_name[i], name))
1336 return label_ids[i];
1337 strcpy(label_name[nlabels], name);
1338 label_ids[nlabels] = LABEL();
1339 return label_ids[nlabels++];
1342 static void readstmt(void)
1344 o_tmpdrop(-1);
1345 nts = 0;
1346 if (!tok_jmp('{')) {
1347 int _nlocals = nlocals;
1348 int _nglobals = nglobals;
1349 int _nenums = nenums;
1350 int _ntypedefs = ntypedefs;
1351 int _nstructs = nstructs;
1352 int _nfuncs = nfuncs;
1353 int _narrays = narrays;
1354 while (tok_jmp('}'))
1355 readstmt();
1356 nlocals = _nlocals;
1357 nenums = _nenums;
1358 ntypedefs = _ntypedefs;
1359 nstructs = _nstructs;
1360 nfuncs = _nfuncs;
1361 narrays = _narrays;
1362 nglobals = _nglobals;
1363 return;
1365 if (!readdefs(localdef, NULL)) {
1366 tok_expect(';');
1367 return;
1369 if (!tok_jmp(TOK_TYPEDEF)) {
1370 readdefs(typedefdef, NULL);
1371 tok_expect(';');
1372 return;
1374 if (!tok_jmp(TOK_IF)) {
1375 int l_fail = LABEL();
1376 int l_end = LABEL();
1377 tok_expect('(');
1378 readexpr();
1379 tok_expect(')');
1380 ts_pop_de(NULL);
1381 o_jz(l_fail);
1382 readstmt();
1383 if (!tok_jmp(TOK_ELSE)) {
1384 o_jmp(l_end);
1385 o_label(l_fail);
1386 readstmt();
1387 o_label(l_end);
1388 } else {
1389 o_label(l_fail);
1391 return;
1393 if (!tok_jmp(TOK_WHILE)) {
1394 int o_break = l_break;
1395 int o_cont = l_cont;
1396 l_break = LABEL();
1397 l_cont = LABEL();
1398 o_label(l_cont);
1399 tok_expect('(');
1400 readexpr();
1401 tok_expect(')');
1402 ts_pop_de(NULL);
1403 o_jz(l_break);
1404 readstmt();
1405 o_jmp(l_cont);
1406 o_label(l_break);
1407 l_break = o_break;
1408 l_cont = o_cont;
1409 return;
1411 if (!tok_jmp(TOK_DO)) {
1412 int o_break = l_break;
1413 int o_cont = l_cont;
1414 int l_beg = LABEL();
1415 l_break = LABEL();
1416 l_cont = LABEL();
1417 o_label(l_beg);
1418 readstmt();
1419 tok_expect(TOK_WHILE);
1420 tok_expect('(');
1421 o_label(l_cont);
1422 readexpr();
1423 ts_pop_de(NULL);
1424 o_jnz(l_beg);
1425 tok_expect(')');
1426 o_label(l_break);
1427 tok_expect(';');
1428 l_break = o_break;
1429 l_cont = o_cont;
1430 return;
1432 if (!tok_jmp(TOK_FOR)) {
1433 int o_break = l_break;
1434 int o_cont = l_cont;
1435 int l_check = LABEL(); /* for condition label */
1436 int l_body = LABEL(); /* for block label */
1437 l_cont = LABEL();
1438 l_break = LABEL();
1439 tok_expect('(');
1440 if (tok_see() != ';')
1441 readestmt();
1442 tok_expect(';');
1443 o_label(l_check);
1444 if (tok_see() != ';') {
1445 readestmt();
1446 ts_pop_de(NULL);
1447 o_jz(l_break);
1449 tok_expect(';');
1450 o_jmp(l_body);
1451 o_label(l_cont);
1452 if (tok_see() != ')')
1453 readestmt();
1454 tok_expect(')');
1455 o_jmp(l_check);
1456 o_label(l_body);
1457 readstmt();
1458 o_jmp(l_cont);
1459 o_label(l_break);
1460 l_break = o_break;
1461 l_cont = o_cont;
1462 return;
1464 if (!tok_jmp(TOK_SWITCH)) {
1465 readswitch();
1466 return;
1468 if (!tok_jmp(TOK_RETURN)) {
1469 int ret = tok_see() != ';';
1470 if (ret) {
1471 readexpr();
1472 ts_pop_de(NULL);
1474 tok_expect(';');
1475 o_ret(ret);
1476 return;
1478 if (!tok_jmp(TOK_BREAK)) {
1479 tok_expect(';');
1480 o_jmp(l_break);
1481 return;
1483 if (!tok_jmp(TOK_CONTINUE)) {
1484 tok_expect(';');
1485 o_jmp(l_cont);
1486 return;
1488 if (!tok_jmp(TOK_GOTO)) {
1489 tok_expect(TOK_NAME);
1490 o_jmp(label_id(tok_id()));
1491 tok_expect(';');
1492 return;
1494 readestmt();
1495 /* labels */
1496 if (!tok_jmp(':')) {
1497 o_label(label_id(tok_id()));
1498 return;
1500 tok_expect(';');
1503 static void readfunc(struct name *name, int flags)
1505 struct funcinfo *fi = &funcs[name->type.id];
1506 int i;
1507 strcpy(func_name, fi->name);
1508 o_func_beg(func_name, fi->nargs, F_GLOBAL(flags), fi->varg);
1509 for (i = 0; i < fi->nargs; i++) {
1510 struct name arg = {"", "", fi->args[i], o_arg2loc(i)};
1511 strcpy(arg.name, fi->argnames[i]);
1512 local_add(&arg);
1514 readstmt();
1515 o_func_end();
1516 func_name[0] = '\0';
1517 nlocals = 0;
1518 label = 0;
1519 nlabels = 0;
1522 static void readdecl(void)
1524 if (!tok_jmp(TOK_TYPEDEF)) {
1525 readdefs(typedefdef, NULL);
1526 tok_expect(';');
1527 return;
1529 readdefs_int(globaldef, NULL);
1530 tok_jmp(';');
1533 static void parse(void)
1535 while (tok_see() != TOK_EOF)
1536 readdecl();
1539 static void compat_macros(void)
1541 cpp_define("__STDC__", "");
1542 cpp_define("__linux__", "");
1543 #ifdef NEATCC_ARM
1544 cpp_define("__arm__", "");
1545 #else
1546 cpp_define("__i386__", "");
1547 #endif
1549 /* ignored keywords */
1550 cpp_define("const", "");
1551 cpp_define("register", "");
1552 cpp_define("volatile", "");
1553 cpp_define("inline", "");
1554 cpp_define("restrict", "");
1555 cpp_define("__inline__", "");
1556 cpp_define("__restrict__", "");
1557 cpp_define("__attribute__(x)", "");
1558 cpp_define("__builtin_va_list__", "long");
1561 int main(int argc, char *argv[])
1563 char obj[128] = "";
1564 int ofd;
1565 int i = 1;
1566 compat_macros();
1567 while (i < argc && argv[i][0] == '-') {
1568 if (argv[i][1] == 'I')
1569 cpp_addpath(argv[i][2] ? argv[i] + 2 : argv[++i]);
1570 if (argv[i][1] == 'D') {
1571 char *name = argv[i] + 2;
1572 char *def = "";
1573 char *eq = strchr(name, '=');
1574 if (eq) {
1575 *eq = '\0';
1576 def = eq + 1;
1578 cpp_define(name, def);
1580 if (argv[i][1] == 'o')
1581 strcpy(obj, argv[i][2] ? argv[i] + 2 : argv[++i]);
1582 i++;
1584 if (i == argc)
1585 die("neatcc: no file given\n");
1586 if (cpp_init(argv[i]))
1587 die("neatcc: cannot open <%s>\n", argv[i]);
1588 parse();
1589 if (!*obj) {
1590 strcpy(obj, argv[i]);
1591 obj[strlen(obj) - 1] = 'o';
1593 ofd = open(obj, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1594 o_write(ofd);
1595 close(ofd);
1596 return 0;
1600 /* parsing function and variable declarations */
1602 /* read the base type of a variable */
1603 static int basetype(struct type *type, unsigned *flags)
1605 int sign = 1;
1606 int size = 4;
1607 int done = 0;
1608 int i = 0;
1609 int isunion;
1610 char name[NAMELEN] = "";
1611 *flags = 0;
1612 type->flags = 0;
1613 type->ptr = 0;
1614 type->addr = 0;
1615 while (!done) {
1616 switch (tok_see()) {
1617 case TOK_STATIC:
1618 *flags |= F_STATIC;
1619 break;
1620 case TOK_EXTERN:
1621 *flags |= F_EXTERN;
1622 break;
1623 case TOK_VOID:
1624 sign = 0;
1625 size = 0;
1626 done = 1;
1627 break;
1628 case TOK_INT:
1629 done = 1;
1630 break;
1631 case TOK_CHAR:
1632 size = 1;
1633 done = 1;
1634 break;
1635 case TOK_SHORT:
1636 size = 2;
1637 break;
1638 case TOK_LONG:
1639 size = LONGSZ;
1640 break;
1641 case TOK_SIGNED:
1642 break;
1643 case TOK_UNSIGNED:
1644 sign = 0;
1645 break;
1646 case TOK_UNION:
1647 case TOK_STRUCT:
1648 isunion = tok_get() == TOK_UNION;
1649 if (!tok_jmp(TOK_NAME))
1650 strcpy(name, tok_id());
1651 if (tok_see() == '{')
1652 type->id = struct_create(name, isunion);
1653 else
1654 type->id = struct_find(name, isunion);
1655 type->flags |= T_STRUCT;
1656 type->bt = LONGSZ;
1657 return 0;
1658 case TOK_ENUM:
1659 tok_get();
1660 tok_jmp(TOK_NAME);
1661 if (tok_see() == '{')
1662 enum_create();
1663 type->bt = 4 | BT_SIGNED;
1664 return 0;
1665 default:
1666 if (tok_see() == TOK_NAME) {
1667 int id = typedef_find(tok_id());
1668 if (id != -1) {
1669 tok_get();
1670 memcpy(type, &typedefs[id].type,
1671 sizeof(*type));
1672 return 0;
1675 if (!i)
1676 return 1;
1677 done = 1;
1678 continue;
1680 i++;
1681 tok_get();
1683 type->bt = size | (sign ? BT_SIGNED : 0);
1684 return 0;
1687 static void readptrs(struct type *type)
1689 while (!tok_jmp('*')) {
1690 type->ptr++;
1691 if (!type->bt)
1692 type->bt = 1;
1696 /* read function arguments */
1697 static int readargs(struct type *args, char argnames[][NAMELEN], int *varg)
1699 int nargs = 0;
1700 tok_expect('(');
1701 *varg = 0;
1702 while (tok_see() != ')') {
1703 if (!tok_jmp(TOK3("..."))) {
1704 *varg = 1;
1705 break;
1707 if (readname(&args[nargs], argnames[nargs], NULL)) {
1708 /* argument has no type, assume int */
1709 tok_expect(TOK_NAME);
1710 memset(&args[nargs], 0, sizeof(struct type));
1711 args[nargs].bt = 4 | BT_SIGNED;
1712 strcpy(argnames[nargs], tok_id());
1714 /* argument arrays are pointers */
1715 array2ptr(&args[nargs]);
1716 nargs++;
1717 if (tok_jmp(','))
1718 break;
1720 tok_expect(')');
1721 /* void argument */
1722 if (nargs == 1 && !TYPE_BT(&args[0]))
1723 return 0;
1724 return nargs;
1727 /* read K&R function arguments */
1728 static void krdef(void *data, struct name *name, unsigned flags)
1730 struct funcinfo *fi = data;
1731 int i;
1732 for (i = 0; i < fi->nargs; i++)
1733 if (!strcmp(fi->argnames[i], name->name))
1734 memcpy(&fi->args[i], &name->type, sizeof(name->type));
1738 * readarrays() parses array specifiers when reading a definition in
1739 * readname(). The "type" parameter contains the type contained in the
1740 * inner array; for instance, type in "int *a[10][20]" would be an int
1741 * pointer. When returning, the "type" parameter is changed to point
1742 * to the final array. The function returns a pointer to the type in
1743 * the inner array; this is useful when the type is not complete yet,
1744 * like when creating an array of function pointers as in
1745 * "int (*f[10])(int)". If there is no array brackets, NULL is returned.
1747 static struct type *readarrays(struct type *type)
1749 long arsz[16];
1750 struct type *inner = NULL;
1751 int nar = 0;
1752 int i;
1753 while (!tok_jmp('[')) {
1754 long n = 0;
1755 if (tok_jmp(']')) {
1756 readexpr();
1757 ts_pop_de(NULL);
1758 if (o_popnum(&n))
1759 err("const expr expected\n");
1760 tok_expect(']');
1762 arsz[nar++] = n;
1764 for (i = nar - 1; i >= 0; i--) {
1765 type->id = array_add(type, arsz[i]);
1766 if (!inner)
1767 inner = &arrays[type->id].type;
1768 type->flags = T_ARRAY;
1769 type->bt = LONGSZ;
1770 type->ptr = 0;
1772 return inner;
1776 * readname() reads a variable definition; the name is copied into
1777 * "name" and the type is copied into "main" argument. The "base"
1778 * argument, if not NULL, indicates the base type of the variable.
1779 * For instance, the base type of "a" and "b" in "int *a, b[10]" is
1780 * "int". If NULL, basetype() is called directly to read the base
1781 * type of the variable. readname() returns zero, only if the
1782 * variable can be read.
1784 static int readname(struct type *main, char *name, struct type *base)
1786 struct type tpool[3];
1787 int npool = 0;
1788 struct type *type = &tpool[npool++];
1789 struct type *ptype = NULL; /* type inside parenthesis */
1790 struct type *btype = NULL; /* type before parenthesis */
1791 struct type *inner;
1792 unsigned flags;
1793 memset(tpool, 0, sizeof(tpool));
1794 if (name)
1795 *name = '\0';
1796 if (!base) {
1797 if (basetype(type, &flags))
1798 return 1;
1799 } else {
1800 memcpy(type, base, sizeof(*base));
1802 readptrs(type);
1803 if (!tok_jmp('(')) {
1804 btype = type;
1805 type = &tpool[npool++];
1806 ptype = type;
1807 readptrs(type);
1809 if (!tok_jmp(TOK_NAME) && name)
1810 strcpy(name, tok_id());
1811 inner = readarrays(type);
1812 if (ptype && inner)
1813 ptype = inner;
1814 if (ptype)
1815 tok_expect(')');
1816 if (tok_see() == '(') {
1817 struct type args[MAXARGS];
1818 char argnames[MAXARGS][NAMELEN];
1819 int varg = 0;
1820 int nargs = readargs(args, argnames, &varg);
1821 if (!ptype) {
1822 btype = type;
1823 type = &tpool[npool++];
1824 ptype = type;
1826 ptype->flags = T_FUNC;
1827 ptype->bt = LONGSZ;
1828 ptype->id = func_create(btype, name, argnames, args, nargs, varg);
1829 if (tok_see() != ';')
1830 while (tok_see() != '{' && !readdefs(krdef, &funcs[ptype->id]))
1831 tok_expect(';');
1832 } else {
1833 if (ptype && readarrays(type))
1834 array2ptr(type);
1836 memcpy(main, type, sizeof(*type));
1837 return 0;
1840 static int readtype(struct type *type)
1842 return readname(type, NULL, NULL);
1846 * readdef() reads a variable definitions statement. The definition
1847 * statement can appear in anywhere: global variables, function
1848 * local variables, struct fields, and typedefs. For each defined
1849 * variable, def() callback is called with the appropriate name
1850 * struct and flags; the callback should finish parsing the definition
1851 * by possibly reading the initializer expression and saving the name
1852 * struct.
1854 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
1855 void *data)
1857 struct type base;
1858 unsigned base_flags;
1859 if (basetype(&base, &base_flags))
1860 return 1;
1861 if (tok_see() == ';' || tok_see() == '{')
1862 return 0;
1863 do {
1864 struct name name = {{""}};
1865 if (readname(&name.type, name.name, &base))
1866 break;
1867 def(data, &name, base_flags);
1868 } while (!tok_jmp(','));
1869 return 0;
1872 /* just like readdefs, but default to int type; for handling K&R functions */
1873 static int readdefs_int(void (*def)(void *data, struct name *name, unsigned flags),
1874 void *data)
1876 struct type base;
1877 unsigned flags = 0;
1878 if (basetype(&base, &flags)) {
1879 if (tok_see() != TOK_NAME)
1880 return 1;
1881 memset(&base, 0, sizeof(base));
1882 base.bt = 4 | BT_SIGNED;
1884 if (tok_see() != ';') {
1885 do {
1886 struct name name = {{""}};
1887 if (readname(&name.type, name.name, &base))
1888 break;
1889 def(data, &name, flags);
1890 } while (!tok_jmp(','));
1892 return 0;
1896 /* parsing initializer expressions */
1898 static void jumpbrace(void)
1900 int depth = 0;
1901 while (tok_see() != '}' || depth--)
1902 if (tok_get() == '{')
1903 depth++;
1904 tok_expect('}');
1907 /* compute the size of the initializer expression */
1908 static int initsize(void)
1910 long addr = tok_addr();
1911 int n = 0;
1912 if (tok_jmp('='))
1913 err("array size unspecified");
1914 if (!tok_jmp(TOK_STR)) {
1915 n = tok_str(NULL);
1916 tok_jump(addr);
1917 return n;
1919 tok_expect('{');
1920 while (tok_jmp('}')) {
1921 long idx = n;
1922 if (!tok_jmp('[')) {
1923 readexpr();
1924 ts_pop_de(NULL);
1925 o_popnum(&idx);
1926 tok_expect(']');
1927 tok_expect('=');
1929 if (n < idx + 1)
1930 n = idx + 1;
1931 while (tok_see() != '}' && tok_see() != ',')
1932 if (tok_get() == '{')
1933 jumpbrace();
1934 tok_jmp(',');
1936 tok_jump(addr);
1937 return n;
1940 static struct type *innertype(struct type *t)
1942 if (t->flags & T_ARRAY && !t->ptr)
1943 return innertype(&arrays[t->id].type);
1944 return t;
1947 /* read the initializer expression and initialize basic types using set() cb */
1948 static void initexpr(struct type *t, int off, void *obj,
1949 void (*set)(void *obj, int off, struct type *t))
1951 if (tok_jmp('{')) {
1952 set(obj, off, t);
1953 return;
1955 if (!t->ptr && t->flags & T_STRUCT) {
1956 struct structinfo *si = &structs[t->id];
1957 int i;
1958 for (i = 0; i < si->nfields && tok_see() != '}'; i++) {
1959 struct name *field = &si->fields[i];
1960 if (!tok_jmp('.')) {
1961 tok_expect(TOK_NAME);
1962 field = struct_field(t->id, tok_id());
1963 tok_expect('=');
1965 initexpr(&field->type, off + field->addr, obj, set);
1966 if (tok_jmp(','))
1967 break;
1969 } else if (t->flags & T_ARRAY) {
1970 struct type *t_de = &arrays[t->id].type;
1971 int i;
1972 /* handling extra braces as in: char s[] = {"sth"} */
1973 if (TYPE_SZ(t_de) == 1 && tok_see() == TOK_STR) {
1974 set(obj, off, t);
1975 tok_expect('}');
1976 return;
1978 for (i = 0; tok_see() != '}'; i++) {
1979 long idx = i;
1980 struct type *it = t_de;
1981 if (!tok_jmp('[')) {
1982 readexpr();
1983 ts_pop_de(NULL);
1984 o_popnum(&idx);
1985 tok_expect(']');
1986 tok_expect('=');
1988 if (tok_see() != '{' && (tok_see() != TOK_STR ||
1989 !(it->flags & T_ARRAY)))
1990 it = innertype(t_de);
1991 initexpr(it, off + type_totsz(it) * idx, obj, set);
1992 if (tok_jmp(','))
1993 break;
1996 tok_expect('}');