ncc: support k&r style function definitions
[neatcc.git] / ncc.c
blob5d059d4e8d09e5612f6904c8800ce17f37088c6c
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_mklabel() (nogen ? 0 : o_mklabel())
39 #define o_jz(addr) (nogen ? 0 : o_jz(addr))
40 #define o_jnz(addr) (nogen ? 0 : o_jnz(addr))
41 #define o_jmp(addr) (nogen ? 0 : o_jmp(addr))
42 #define o_filljmp(addr) {if (!nogen) o_filljmp(addr);}
43 #define o_filljmp2(addr, dst) {if (!nogen) o_filljmp2(addr, dst);}
44 #define o_fork() {if (!nogen) o_fork();}
45 #define o_forkpush() {if (!nogen) o_forkpush();}
46 #define o_forkjoin() {if (!nogen) o_forkjoin();}
48 #define MAXLOCALS (1 << 10)
49 #define MAXGLOBALS (1 << 10)
50 #define MAXARGS (1 << 5)
52 #define ALIGN(x, a) (((x) + (a) - 1) & ~((a) - 1))
53 #define MIN(a, b) ((a) < (b) ? (a) : (b))
55 #define TYPE_BT(t) ((t)->ptr ? LONGSZ : (t)->bt)
56 #define TYPE_SZ(t) ((t)->ptr ? LONGSZ : (t)->bt & BT_SZMASK)
58 /* type->flag values */
59 #define T_ARRAY 0x01
60 #define T_STRUCT 0x02
61 #define T_FUNC 0x04
63 /* variable definition flags */
64 #define F_STATIC 0x01
65 #define F_EXTERN 0x02
67 struct type {
68 unsigned bt;
69 unsigned flags;
70 int ptr;
71 int id; /* for structs, functions and arrays */
72 int addr; /* the address is passed to gen.c; deref for value */
75 /* type stack */
76 static struct type ts[MAXTMP];
77 static int nts;
79 static void ts_push_bt(unsigned bt)
81 ts[nts].ptr = 0;
82 ts[nts].flags = 0;
83 ts[nts].addr = 0;
84 ts[nts++].bt = bt;
87 static void ts_push(struct type *t)
89 struct type *d = &ts[nts++];
90 memcpy(d, t, sizeof(*t));
93 static void ts_push_addr(struct type *t)
95 ts_push(t);
96 ts[nts - 1].addr = 1;
99 static void ts_pop(struct type *type)
101 nts--;
102 if (type)
103 *type = ts[nts];
106 void err(char *msg)
108 die("%s: %s", cpp_loc(tok_addr()), msg);
111 struct name {
112 char name[NAMELEN];
113 char elfname[NAMELEN]; /* local elf name for static variables in function */
114 struct type type;
115 long addr; /* local stack offset, global data addr, struct offset */
118 static struct name locals[MAXLOCALS];
119 static int nlocals;
120 static struct name globals[MAXGLOBALS];
121 static int nglobals;
123 static void local_add(struct name *name)
125 if (nlocals >= MAXLOCALS)
126 err("nomem: MAXLOCALS reached!\n");
127 memcpy(&locals[nlocals++], name, sizeof(*name));
130 static int local_find(char *name)
132 int i;
133 for (i = nlocals - 1; i >= 0; --i)
134 if (!strcmp(locals[i].name, name))
135 return i;
136 return -1;
139 static int global_find(char *name)
141 int i;
142 for (i = nglobals - 1; i >= 0; i--)
143 if (!strcmp(name, globals[i].name))
144 return i;
145 return -1;
148 static void global_add(struct name *name)
150 if (nglobals >= MAXGLOBALS)
151 err("nomem: MAXGLOBALS reached!\n");
152 memcpy(&globals[nglobals++], name, sizeof(*name));
155 #define MAXENUMS (1 << 10)
157 static struct enumval {
158 char name[NAMELEN];
159 int n;
160 } enums[MAXENUMS];
161 static int nenums;
163 static void enum_add(char *name, int val)
165 struct enumval *ev = &enums[nenums++];
166 if (nenums >= MAXENUMS)
167 err("nomem: MAXENUMS reached!\n");
168 strcpy(ev->name, name);
169 ev->n = val;
172 static int enum_find(int *val, char *name)
174 int i;
175 for (i = nenums - 1; i >= 0; --i)
176 if (!strcmp(name, enums[i].name)) {
177 *val = enums[i].n;
178 return 0;
180 return 1;
183 #define MAXTYPEDEFS (1 << 10)
185 static struct typdefinfo {
186 char name[NAMELEN];
187 struct type type;
188 } typedefs[MAXTYPEDEFS];
189 static int ntypedefs;
191 static void typedef_add(char *name, struct type *type)
193 struct typdefinfo *ti = &typedefs[ntypedefs++];
194 if (ntypedefs >= MAXTYPEDEFS)
195 err("nomem: MAXTYPEDEFS reached!\n");
196 strcpy(ti->name, name);
197 memcpy(&ti->type, type, sizeof(*type));
200 static int typedef_find(char *name)
202 int i;
203 for (i = ntypedefs - 1; i >= 0; --i)
204 if (!strcmp(name, typedefs[i].name))
205 return i;
206 return -1;
209 #define MAXARRAYS (1 << 10)
211 static struct array {
212 struct type type;
213 int n;
214 } arrays[MAXARRAYS];
215 static int narrays;
217 static int array_add(struct type *type, int n)
219 struct array *a = &arrays[narrays++];
220 if (narrays >= MAXARRAYS)
221 err("nomem: MAXARRAYS reached!\n");
222 memcpy(&a->type, type, sizeof(*type));
223 a->n = n;
224 return a - arrays;
227 static void array2ptr(struct type *t)
229 if (t->flags & T_ARRAY && !t->ptr) {
230 memcpy(t, &arrays[t->id].type, sizeof(*t));
231 t->ptr++;
235 #define MAXSTRUCTS (1 << 10)
236 #define MAXFIELDS (1 << 7)
238 static struct structinfo {
239 char name[NAMELEN];
240 struct name fields[MAXFIELDS];
241 int nfields;
242 int isunion;
243 int size;
244 } structs[MAXSTRUCTS];
245 static int nstructs;
247 static int struct_find(char *name, int isunion)
249 int i;
250 for (i = nstructs - 1; i >= 0; --i)
251 if (*structs[i].name && !strcmp(name, structs[i].name) &&
252 structs[i].isunion == isunion)
253 return i;
254 i = nstructs++;
255 if (nstructs >= MAXSTRUCTS)
256 err("nomem: MAXTYPES reached!\n");
257 memset(&structs[i], 0, sizeof(structs[i]));
258 strcpy(structs[i].name, name);
259 structs[i].isunion = isunion;
260 return i;
263 static struct name *struct_field(int id, char *name)
265 struct structinfo *si = &structs[id];
266 int i;
267 for (i = 0; i < si->nfields; i++)
268 if (!strcmp(name, si->fields[i].name))
269 return &si->fields[i];
270 err("field not found\n");
273 #define MAXBREAK (1 << 7)
275 static long breaks[MAXBREAK];
276 static int nbreaks;
277 static long continues[MAXBREAK];
278 static int ncontinues;
280 static void break_fill(long addr, int till)
282 int i;
283 for (i = till; i < nbreaks; i++)
284 o_filljmp2(breaks[i], addr);
285 nbreaks = till;
288 static void continue_fill(long addr, int till)
290 int i;
291 for (i = till; i < ncontinues; i++)
292 o_filljmp2(continues[i], addr);
293 ncontinues = till;
296 /* return t's size */
297 static int type_totsz(struct type *t)
299 if (t->ptr)
300 return LONGSZ;
301 if (t->flags & T_ARRAY)
302 return arrays[t->id].n * type_totsz(&arrays[t->id].type);
303 return t->flags & T_STRUCT ? structs[t->id].size : BT_SZ(t->bt);
306 /* return t's dereferenced size */
307 static unsigned type_szde(struct type *t)
309 struct type de = *t;
310 array2ptr(&de);
311 de.ptr--;
312 return type_totsz(&de);
315 /* dereference stack top if t->addr (ie. address is pushed to gen.c) */
316 static void ts_de(int deref)
318 struct type *t = &ts[nts - 1];
319 array2ptr(t);
320 if (deref && t->addr && (t->ptr || !(t->flags & T_FUNC)))
321 o_deref(TYPE_BT(t));
322 t->addr = 0;
325 /* pop stack pop to *t and dereference if t->addr */
326 static void ts_pop_de(struct type *t)
328 ts_de(1);
329 ts_pop(t);
332 /* pop the top 2 stack values and dereference them if t->addr */
333 static void ts_pop_de2(struct type *t1, struct type *t2)
335 ts_pop_de(t1);
336 o_tmpswap();
337 ts_pop_de(t2);
338 o_tmpswap();
341 static int tok_jmp(int tok)
343 if (tok_see() != tok)
344 return 1;
345 tok_get();
346 return 0;
349 static void tok_expect(int tok)
351 if (tok_get() != tok)
352 err("syntax error\n");
355 static unsigned bt_op(unsigned bt1, unsigned bt2)
357 unsigned s1 = BT_SZ(bt1);
358 unsigned s2 = BT_SZ(bt2);
359 return (bt1 | bt2) & BT_SIGNED | (s1 > s2 ? s1 : s2);
362 static void ts_binop(int op)
364 struct type t1, t2;
365 int bt;
366 ts_pop_de2(&t1, &t2);
367 if (op == O_DIV || op == O_MOD)
368 bt = TYPE_BT(&t2);
369 else
370 bt = bt_op(TYPE_BT(&t1), TYPE_BT(&t2));
371 o_bop(op | (bt & BT_SIGNED ? O_SIGNED : 0));
372 ts_push_bt(bt);
375 static void ts_addop(int op)
377 struct type t1, t2;
378 ts_pop_de2(&t1, &t2);
379 if (!t1.ptr && !t2.ptr) {
380 o_bop(op);
381 ts_push_bt(bt_op(TYPE_BT(&t1), TYPE_BT(&t2)));
382 return;
384 if (t1.ptr && !t2.ptr)
385 o_tmpswap();
386 if (!t1.ptr && t2.ptr)
387 if (type_szde(&t2) > 1) {
388 o_num(type_szde(&t2));
389 o_bop(O_MUL);
391 if (t1.ptr && !t2.ptr)
392 o_tmpswap();
393 o_bop(op);
394 if (t1.ptr && t2.ptr) {
395 int sz = type_szde(&t1);
396 if (sz > 1) {
397 o_num(sz);
398 o_bop(O_DIV);
400 ts_push_bt(4 | BT_SIGNED);
401 } else {
402 ts_push(t1.ptr ? &t1 : &t2);
406 /* function prototypes for parsing function and variable declarations */
407 static int readname(struct type *main, char *name, struct type *base);
408 static int readtype(struct type *type);
409 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
410 void *data);
411 static int readdefs_int(void (*def)(void *data, struct name *name, unsigned flags),
412 void *data);
414 /* function prototypes for parsing initializer expressions */
415 static int initsize(void);
416 static void initexpr(struct type *t, int off, void *obj,
417 void (*set)(void *obj, int off, struct type *t));
419 static int type_alignment(struct type *t)
421 if (t->flags & T_ARRAY && !t->ptr)
422 return type_alignment(&arrays[t->id].type);
423 if (t->flags & T_STRUCT && !t->ptr)
424 return type_alignment(&structs[t->id].fields[0].type);
425 return MIN(LONGSZ, type_totsz(t));
428 static void structdef(void *data, struct name *name, unsigned flags)
430 struct structinfo *si = data;
431 if (si->isunion) {
432 name->addr = 0;
433 if (si->size < type_totsz(&name->type))
434 si->size = type_totsz(&name->type);
435 } else {
436 struct type *t = &name->type;
437 int alignment = type_alignment(t);
438 if (t->flags & T_ARRAY && !t->ptr)
439 alignment = MIN(LONGSZ, type_totsz(&arrays[t->id].type));
440 si->size = ALIGN(si->size, alignment);
441 name->addr = si->size;
442 si->size += type_totsz(&name->type);
444 memcpy(&si->fields[si->nfields++], name, sizeof(*name));
447 static int struct_create(char *name, int isunion)
449 int id = struct_find(name, isunion);
450 struct structinfo *si = &structs[id];
451 tok_expect('{');
452 while (tok_jmp('}')) {
453 readdefs(structdef, si);
454 tok_expect(';');
456 return id;
459 static void readexpr(void);
461 static void enum_create(void)
463 long n = 0;
464 tok_expect('{');
465 while (tok_jmp('}')) {
466 char name[NAMELEN];
467 tok_expect(TOK_NAME);
468 strcpy(name, tok_id());
469 if (!tok_jmp('=')) {
470 readexpr();
471 ts_pop_de(NULL);
472 if (o_popnum(&n))
473 err("const expr expected!\n");
475 enum_add(name, n++);
476 tok_jmp(',');
480 /* used to differenciate labels from case and cond exprs */
481 static int ncexpr;
482 static int caseexpr;
484 static void readpre(void);
486 static char *tmp_str(char *buf, int len)
488 static char name[NAMELEN];
489 static int id;
490 void *dat;
491 sprintf(name, "__neatcc.s%d", id++);
492 dat = o_mkdat(name, len, 0);
493 memcpy(dat, buf, len);
494 return name;
497 static void readprimary(void)
499 if (!tok_jmp(TOK_NUM)) {
500 long n;
501 int bt = tok_num(&n);
502 ts_push_bt(bt);
503 o_num(n);
504 return;
506 if (!tok_jmp(TOK_STR)) {
507 struct type t;
508 char buf[BUFSIZE];
509 int len;
510 t.bt = 1 | BT_SIGNED;
511 t.ptr = 1;
512 t.addr = 0;
513 t.flags = 0;
514 ts_push(&t);
515 len = tok_str(buf);
516 o_sym(tmp_str(buf, len));
517 return;
519 if (!tok_jmp(TOK_NAME)) {
520 struct name unkn = {""};
521 char *name = unkn.name;
522 int n;
523 strcpy(name, tok_id());
524 /* don't search for labels here */
525 if (!ncexpr && !caseexpr && tok_see() == ':')
526 return;
527 if ((n = local_find(name)) != -1) {
528 struct name *l = &locals[n];
529 o_local(l->addr);
530 ts_push_addr(&l->type);
531 return;
533 if ((n = global_find(name)) != -1) {
534 struct name *g = &globals[n];
535 o_sym(*g->elfname ? g->elfname : g->name);
536 ts_push_addr(&g->type);
537 return;
539 if (!enum_find(&n, name)) {
540 ts_push_bt(4 | BT_SIGNED);
541 o_num(n);
542 return;
544 if (tok_see() != '(')
545 err("unknown symbol\n");
546 global_add(&unkn);
547 ts_push_bt(LONGSZ);
548 o_sym(unkn.name);
549 return;
551 if (!tok_jmp('(')) {
552 struct type t;
553 if (!readtype(&t)) {
554 struct type o;
555 tok_expect(')');
556 readpre();
557 ts_pop_de(&o);
558 ts_push(&t);
559 if (!t.ptr || !o.ptr)
560 o_cast(TYPE_BT(&t));
561 } else {
562 readexpr();
563 while (tok_jmp(')')) {
564 tok_expect(',');
565 ts_pop(NULL);
566 o_tmpdrop(1);
567 readexpr();
570 return;
574 static void arrayderef(void)
576 struct type t;
577 int sz;
578 ts_pop_de(NULL);
579 ts_pop(&t);
580 if (!(t.flags & T_ARRAY && !t.ptr) && t.addr) {
581 o_tmpswap();
582 o_deref(TYPE_BT(&t));
583 o_tmpswap();
585 array2ptr(&t);
586 t.ptr--;
587 sz = type_totsz(&t);
588 t.addr = 1;
589 if (sz > 1) {
590 o_num(sz);
591 o_bop(O_MUL);
593 o_bop(O_ADD);
594 ts_push(&t);
597 static void inc_post(int op)
599 struct type t = ts[nts - 1];
600 /* pushing the value before inc */
601 o_tmpcopy();
602 ts_de(1);
603 o_load();
604 o_tmpswap();
606 /* increment by 1 or pointer size */
607 o_tmpcopy();
608 ts_push(&t);
609 ts_pop_de(&t);
610 o_num(t.ptr > 0 ? type_szde(&t) : 1);
611 o_bop(op);
613 /* assign back */
614 o_assign(TYPE_BT(&t));
615 o_tmpdrop(1);
618 static void readfield(void)
620 struct name *field;
621 struct type t;
622 tok_expect(TOK_NAME);
623 ts_pop(&t);
624 array2ptr(&t);
625 field = struct_field(t.id, tok_id());
626 if (field->addr) {
627 o_num(field->addr);
628 o_bop(O_ADD);
630 ts_push_addr(&field->type);
633 #define MAXFUNCS (1 << 10)
635 static struct funcinfo {
636 struct type args[MAXARGS];
637 struct type ret;
638 int nargs;
639 int varg;
640 /* function and argument names; useful only when defining */
641 char argnames[MAXARGS][NAMELEN];
642 char name[NAMELEN];
643 } funcs[MAXFUNCS];
644 static int nfuncs;
646 static int func_create(struct type *ret, char *name, char argnames[][NAMELEN],
647 struct type *args, int nargs, int varg)
649 struct funcinfo *fi = &funcs[nfuncs++];
650 int i;
651 if (nfuncs >= MAXFUNCS)
652 err("nomem: MAXFUNCS reached!\n");
653 memcpy(&fi->ret, ret, sizeof(*ret));
654 for (i = 0; i < nargs; i++)
655 memcpy(&fi->args[i], &args[i], sizeof(*ret));
656 fi->nargs = nargs;
657 fi->varg = varg;
658 strcpy(fi->name, name);
659 for (i = 0; i < nargs; i++)
660 strcpy(fi->argnames[i], argnames[i]);
661 return fi - funcs;
664 static void readcall(void)
666 struct type t;
667 struct funcinfo *fi;
668 int argc = 0;
669 ts_pop(&t);
670 if (t.flags & T_FUNC && t.ptr > 0)
671 o_deref(LONGSZ);
672 fi = t.flags & T_FUNC ? &funcs[t.id] : NULL;
673 if (tok_see() != ')') {
674 do {
675 readexpr();
676 ts_pop_de(NULL);
677 argc++;
678 } while (!tok_jmp(','));
680 tok_expect(')');
681 o_call(argc, fi ? TYPE_BT(&fi->ret) : 4 | BT_SIGNED);
682 if (fi) {
683 if (TYPE_BT(&fi->ret))
684 o_cast(TYPE_BT(&fi->ret));
685 ts_push(&fi->ret);
686 } else {
687 ts_push_bt(4 | BT_SIGNED);
691 static void readpost(void)
693 readprimary();
694 while (1) {
695 if (!tok_jmp('[')) {
696 readexpr();
697 tok_expect(']');
698 arrayderef();
699 continue;
701 if (!tok_jmp('(')) {
702 readcall();
703 continue;
705 if (!tok_jmp(TOK2("++"))) {
706 inc_post(O_ADD);
707 continue;
709 if (!tok_jmp(TOK2("--"))) {
710 inc_post(O_SUB);
711 continue;
713 if (!tok_jmp('.')) {
714 readfield();
715 continue;
717 if (!tok_jmp(TOK2("->"))) {
718 ts_de(1);
719 readfield();
720 continue;
722 break;
726 static void inc_pre(int op)
728 struct type t;
729 readpre();
730 /* copy the destination */
731 o_tmpcopy();
732 ts_push(&ts[nts - 1]);
733 /* increment by 1 or pointer size */
734 ts_pop_de(&t);
735 o_num(t.ptr > 0 ? type_szde(&t) : 1);
736 o_bop(op);
737 /* assign the result */
738 o_assign(TYPE_BT(&t));
739 ts_de(0);
742 static void readpre(void)
744 if (!tok_jmp('&')) {
745 struct type type;
746 readpre();
747 ts_pop(&type);
748 if (!type.addr)
749 err("cannot use the address\n");
750 type.ptr++;
751 type.addr = 0;
752 ts_push(&type);
753 return;
755 if (!tok_jmp('*')) {
756 struct type t;
757 readpre();
758 ts_pop(&t);
759 array2ptr(&t);
760 if (!t.ptr)
761 err("dereferencing non-pointer\n");
762 if (t.addr)
763 o_deref(TYPE_BT(&t));
764 t.ptr--;
765 t.addr = 1;
766 ts_push(&t);
767 return;
769 if (!tok_jmp('!')) {
770 readpre();
771 ts_pop_de(NULL);
772 o_uop(O_LNOT);
773 ts_push_bt(4 | BT_SIGNED);
774 return;
776 if (!tok_jmp('-')) {
777 readpre();
778 ts_de(1);
779 o_uop(O_NEG);
780 return;
782 if (!tok_jmp('~')) {
783 readpre();
784 ts_de(1);
785 o_uop(O_NOT);
786 return;
788 if (!tok_jmp(TOK2("++"))) {
789 inc_pre(O_ADD);
790 return;
792 if (!tok_jmp(TOK2("--"))) {
793 inc_pre(O_SUB);
794 return;
796 if (!tok_jmp(TOK_SIZEOF)) {
797 struct type t;
798 int op = !tok_jmp('(');
799 if (readtype(&t)) {
800 nogen++;
801 if (op)
802 readexpr();
803 else
804 readpre();
805 nogen--;
806 ts_pop(&t);
808 ts_push_bt(4);
809 o_num(type_totsz(&t));
810 if (op)
811 tok_expect(')');
812 return;
814 readpost();
817 static void readmul(void)
819 readpre();
820 while (1) {
821 if (!tok_jmp('*')) {
822 readpre();
823 ts_binop(O_MUL);
824 continue;
826 if (!tok_jmp('/')) {
827 readpre();
828 ts_binop(O_DIV);
829 continue;
831 if (!tok_jmp('%')) {
832 readpre();
833 ts_binop(O_MOD);
834 continue;
836 break;
840 static void readadd(void)
842 readmul();
843 while (1) {
844 if (!tok_jmp('+')) {
845 readmul();
846 ts_addop(O_ADD);
847 continue;
849 if (!tok_jmp('-')) {
850 readmul();
851 ts_addop(O_SUB);
852 continue;
854 break;
858 static void shift(int op)
860 struct type t;
861 readadd();
862 ts_pop_de2(NULL, &t);
863 o_bop(op | (BT_SIGNED & TYPE_BT(&t) ? O_SIGNED : 0));
864 ts_push_bt(TYPE_BT(&t));
867 static void readshift(void)
869 readadd();
870 while (1) {
871 if (!tok_jmp(TOK2("<<"))) {
872 shift(O_SHL);
873 continue;
875 if (!tok_jmp(TOK2(">>"))) {
876 shift(O_SHR);
877 continue;
879 break;
883 static void cmp(int op)
885 struct type t1, t2;
886 int bt;
887 readshift();
888 ts_pop_de2(&t1, &t2);
889 bt = bt_op(TYPE_BT(&t1), TYPE_BT(&t2));
890 o_bop(op | (bt & BT_SIGNED ? O_SIGNED : 0));
891 ts_push_bt(4 | BT_SIGNED);
894 static void readcmp(void)
896 readshift();
897 while (1) {
898 if (!tok_jmp('<')) {
899 cmp(O_LT);
900 continue;
902 if (!tok_jmp('>')) {
903 cmp(O_GT);
904 continue;
906 if (!tok_jmp(TOK2("<="))) {
907 cmp(O_LE);
908 continue;
910 if (!tok_jmp(TOK2(">="))) {
911 cmp(O_GE);
912 continue;
914 break;
918 static void eq(int op)
920 readcmp();
921 ts_pop_de2(NULL, NULL);
922 o_bop(op);
923 ts_push_bt(4 | BT_SIGNED);
926 static void readeq(void)
928 readcmp();
929 while (1) {
930 if (!tok_jmp(TOK2("=="))) {
931 eq(O_EQ);
932 continue;
934 if (!tok_jmp(TOK2("!="))) {
935 eq(O_NEQ);
936 continue;
938 break;
942 static void readbitand(void)
944 readeq();
945 while (!tok_jmp('&')) {
946 readeq();
947 ts_binop(O_AND);
951 static void readxor(void)
953 readbitand();
954 while (!tok_jmp('^')) {
955 readbitand();
956 ts_binop(O_XOR);
960 static void readbitor(void)
962 readxor();
963 while (!tok_jmp('|')) {
964 readxor();
965 ts_binop(O_OR);
969 #define MAXCOND (1 << 7)
971 static void readand(void)
973 long conds[MAXCOND];
974 int nconds = 0;
975 long passed;
976 int i;
977 readbitor();
978 if (tok_see() != TOK2("&&"))
979 return;
980 o_fork();
981 ts_pop_de(NULL);
982 conds[nconds++] = o_jz(0);
983 while (!tok_jmp(TOK2("&&"))) {
984 readbitor();
985 ts_pop_de(NULL);
986 conds[nconds++] = o_jz(0);
988 o_num(1);
989 o_forkpush();
990 passed = o_jmp(0);
991 for (i = 0; i < nconds; i++)
992 o_filljmp(conds[i]);
993 o_num(0);
994 o_forkpush();
995 o_forkjoin();
996 o_filljmp(passed);
997 ts_push_bt(4 | BT_SIGNED);
1000 static void reador(void)
1002 long conds[MAXCOND];
1003 int nconds = 0;
1004 long failed;
1005 int i;
1006 readand();
1007 if (tok_see() != TOK2("||"))
1008 return;
1009 o_fork();
1010 ts_pop_de(NULL);
1011 conds[nconds++] = o_jnz(0);
1012 while (!tok_jmp(TOK2("||"))) {
1013 readand();
1014 ts_pop_de(NULL);
1015 conds[nconds++] = o_jnz(0);
1017 o_num(0);
1018 o_forkpush();
1019 failed = o_jmp(0);
1020 for (i = 0; i < nconds; i++)
1021 o_filljmp(conds[i]);
1022 o_num(1);
1023 o_forkpush();
1024 o_forkjoin();
1025 o_filljmp(failed);
1026 ts_push_bt(4 | BT_SIGNED);
1029 static void readcexpr(void);
1031 static int readcexpr_const(void)
1033 long c;
1034 if (o_popnum(&c))
1035 return -1;
1036 if (!c)
1037 nogen++;
1038 readcexpr();
1039 /* both branches yield the same type; so ignore the first */
1040 ts_pop_de(NULL);
1041 tok_expect(':');
1042 if (c)
1043 nogen++;
1044 else
1045 nogen--;
1046 readcexpr();
1047 /* making sure t->addr == 0 on both branches */
1048 ts_de(1);
1049 if (c)
1050 nogen--;
1051 return 0;
1054 static void readcexpr(void)
1056 long l1, l2;
1057 reador();
1058 if (tok_jmp('?'))
1059 return;
1060 ncexpr++;
1061 ts_pop_de(NULL);
1062 o_fork();
1063 if (readcexpr_const()) {
1064 l1 = o_jz(0);
1065 readcexpr();
1066 /* both branches yield the same type; so ignore the first */
1067 ts_pop_de(NULL);
1068 o_forkpush();
1069 l2 = o_jmp(0);
1071 tok_expect(':');
1072 o_filljmp(l1);
1073 readcexpr();
1074 /* making sure t->addr == 0 on both branches */
1075 ts_de(1);
1076 o_forkpush();
1077 o_forkjoin();
1078 o_filljmp(l2);
1080 ncexpr--;
1083 static void opassign(int op, int ptrop)
1085 struct type t = ts[nts - 1];
1086 o_tmpcopy();
1087 ts_push(&t);
1088 readexpr();
1089 ts_addop(op);
1090 o_assign(TYPE_BT(&ts[nts - 2]));
1091 ts_pop(NULL);
1092 ts_de(0);
1095 static void doassign(void)
1097 struct type t = ts[nts - 1];
1098 if (!t.ptr && t.flags & T_STRUCT) {
1099 ts_pop(NULL);
1100 o_num(type_totsz(&t));
1101 o_memcpy();
1102 } else {
1103 ts_pop_de(NULL);
1104 o_assign(TYPE_BT(&ts[nts - 1]));
1105 ts_de(0);
1109 static void readexpr(void)
1111 readcexpr();
1112 if (!tok_jmp('=')) {
1113 readexpr();
1114 doassign();
1115 return;
1117 if (!tok_jmp(TOK2("+="))) {
1118 opassign(O_ADD, 1);
1119 return;
1121 if (!tok_jmp(TOK2("-="))) {
1122 opassign(O_SUB, 1);
1123 return;
1125 if (!tok_jmp(TOK2("*="))) {
1126 opassign(O_MUL, 0);
1127 return;
1129 if (!tok_jmp(TOK2("/="))) {
1130 opassign(O_DIV, 0);
1131 return;
1133 if (!tok_jmp(TOK2("%="))) {
1134 opassign(O_MOD, 0);
1135 return;
1137 if (!tok_jmp(TOK3("<<="))) {
1138 opassign(O_SHL, 0);
1139 return;
1141 if (!tok_jmp(TOK3(">>="))) {
1142 opassign(O_SHR, 0);
1143 return;
1145 if (!tok_jmp(TOK3("&="))) {
1146 opassign(O_AND, 0);
1147 return;
1149 if (!tok_jmp(TOK3("|="))) {
1150 opassign(O_OR, 0);
1151 return;
1153 if (!tok_jmp(TOK3("^="))) {
1154 opassign(O_XOR, 0);
1155 return;
1159 static void readestmt(void)
1161 do {
1162 o_tmpdrop(-1);
1163 nts = 0;
1164 readexpr();
1165 } while (!tok_jmp(','));
1168 #define F_GLOBAL(flags) (!((flags) & F_STATIC))
1170 static void globalinit(void *obj, int off, struct type *t)
1172 struct name *name = obj;
1173 char *elfname = *name->elfname ? name->elfname : name->name;
1174 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1175 struct type *t_de = &arrays[t->id].type;
1176 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1177 char buf[BUFSIZE];
1178 int len;
1179 tok_expect(TOK_STR);
1180 len = tok_str(buf);
1181 memcpy((void *) name->addr + off, buf, len);
1182 return;
1185 readexpr();
1186 o_datset(elfname, off, TYPE_BT(t));
1187 ts_pop(NULL);
1190 static void readfunc(struct name *name, int flags);
1192 static void globaldef(void *data, struct name *name, unsigned flags)
1194 struct type *t = &name->type;
1195 char *elfname = *name->elfname ? name->elfname : name->name;
1196 int sz;
1197 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1198 if (~flags & F_EXTERN)
1199 arrays[t->id].n = initsize();
1200 sz = type_totsz(t);
1201 if (!(flags & F_EXTERN) && (!(t->flags & T_FUNC) || t->ptr)) {
1202 if (tok_see() == '=')
1203 name->addr = (long) o_mkdat(elfname, sz, F_GLOBAL(flags));
1204 else
1205 o_mkbss(elfname, sz, F_GLOBAL(flags));
1207 global_add(name);
1208 if (!tok_jmp('='))
1209 initexpr(t, 0, name, globalinit);
1210 if (tok_see() == '{' && name->type.flags & T_FUNC)
1211 readfunc(name, flags);
1214 /* generate the address of local + off */
1215 static void o_localoff(long addr, int off)
1217 o_local(addr);
1218 if (off) {
1219 o_num(off);
1220 o_bop(O_ADD);
1224 static void localinit(void *obj, int off, struct type *t)
1226 long addr = *(long *) obj;
1227 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1228 struct type *t_de = &arrays[t->id].type;
1229 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1230 char buf[BUFSIZE];
1231 int len;
1232 tok_expect(TOK_STR);
1233 len = tok_str(buf);
1234 o_localoff(addr, off);
1235 o_sym(tmp_str(buf, len));
1236 o_num(len);
1237 o_memcpy();
1238 o_tmpdrop(1);
1239 return;
1242 o_localoff(addr, off);
1243 ts_push(t);
1244 readexpr();
1245 doassign();
1246 ts_pop(NULL);
1247 o_tmpdrop(1);
1250 /* current function name */
1251 static char func_name[NAMELEN];
1253 static void localdef(void *data, struct name *name, unsigned flags)
1255 struct type *t = &name->type;
1256 if ((flags & F_EXTERN) || (t->flags & T_FUNC) && !t->ptr) {
1257 global_add(name);
1258 return;
1260 if (flags & F_STATIC) {
1261 sprintf(name->elfname, "__neatcc.%s.%s", func_name, name->name);
1262 globaldef(data, name, flags);
1263 return;
1265 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1266 arrays[t->id].n = initsize();
1267 name->addr = o_mklocal(type_totsz(&name->type));
1268 local_add(name);
1269 if (!tok_jmp('=')) {
1270 if (t->flags & (T_ARRAY | T_STRUCT) && !t->ptr) {
1271 o_local(name->addr);
1272 o_num(0);
1273 o_num(type_totsz(t));
1274 o_memset();
1275 o_tmpdrop(1);
1277 initexpr(t, 0, &name->addr, localinit);
1281 /* read K&R function arguments */
1282 void krdef(void *data, struct name *name, unsigned flags)
1284 struct funcinfo *fi = data;
1285 int i;
1286 for (i = 0; i < fi->nargs; i++)
1287 if (!strcmp(fi->argnames[i], name->name))
1288 memcpy(&fi->args[i], &name->type, sizeof(name->type));
1291 static void typedefdef(void *data, struct name *name, unsigned flags)
1293 typedef_add(name->name, &name->type);
1296 static void readstmt(void);
1298 #define MAXCASES (1 << 7)
1300 static void readswitch(void)
1302 int break_beg = nbreaks;
1303 long val_addr = o_mklocal(LONGSZ);
1304 struct type t;
1305 int ncases = 0; /* number of case labels */
1306 long last_failed = -1; /* address of last failed jmp */
1307 long last_matched = -1; /* address of last walk through jmp */
1308 long default_addr = -1; /* address of the default label */
1309 tok_expect('(');
1310 readexpr();
1311 ts_pop_de(&t);
1312 o_local(val_addr);
1313 o_tmpswap();
1314 o_assign(TYPE_BT(&t));
1315 ts_de(0);
1316 o_tmpdrop(1);
1317 tok_expect(')');
1318 tok_expect('{');
1319 while (tok_jmp('}')) {
1320 if (tok_see() != TOK_CASE && tok_see() != TOK_DEFAULT) {
1321 readstmt();
1322 continue;
1324 if (ncases)
1325 last_matched = o_jmp(0);
1326 if (tok_get() == TOK_CASE) {
1327 if (last_failed >= 0)
1328 o_filljmp(last_failed);
1329 caseexpr = 1;
1330 readexpr();
1331 ts_pop_de(NULL);
1332 caseexpr = 0;
1333 o_local(val_addr);
1334 o_deref(TYPE_BT(&t));
1335 o_bop(O_EQ);
1336 last_failed = o_jz(0);
1337 o_tmpdrop(1);
1338 } else {
1339 if (!ncases)
1340 last_failed = o_jmp(0);
1341 default_addr = o_mklabel();
1343 tok_expect(':');
1344 if (last_matched >= 0)
1345 o_filljmp(last_matched);
1346 ncases++;
1348 o_rmlocal(val_addr, LONGSZ);
1349 if (last_failed >= 0)
1350 o_filljmp2(last_failed,
1351 default_addr >= 0 ? default_addr : o_mklabel());
1352 break_fill(o_mklabel(), break_beg);
1355 #define MAXGOTO (1 << 10)
1357 static struct gotoinfo {
1358 char name[NAMELEN];
1359 long addr;
1360 } gotos[MAXGOTO];
1361 static int ngotos;
1363 static struct labelinfo {
1364 char name[NAMELEN];
1365 long addr;
1366 } labels[MAXGOTO];
1367 static int nlabels;
1369 static void goto_add(char *name)
1371 strcpy(gotos[ngotos].name, name);
1372 gotos[ngotos++].addr = o_jmp(0);
1375 static void label_add(char *name)
1377 strcpy(labels[nlabels].name, name);
1378 labels[nlabels++].addr = o_mklabel();
1381 static void goto_fill(void)
1383 int i, j;
1384 for (i = 0; i < ngotos; i++)
1385 for (j = 0; j < nlabels; j++)
1386 if (!strcmp(gotos[i].name, labels[j].name)) {
1387 o_filljmp2(gotos[i].addr, labels[j].addr);
1388 break;
1392 static void readstmt(void)
1394 o_tmpdrop(-1);
1395 nts = 0;
1396 if (!tok_jmp('{')) {
1397 int _nlocals = nlocals;
1398 int _nglobals = nglobals;
1399 int _nenums = nenums;
1400 int _ntypedefs = ntypedefs;
1401 int _nstructs = nstructs;
1402 int _nfuncs = nfuncs;
1403 int _narrays = narrays;
1404 while (tok_jmp('}'))
1405 readstmt();
1406 nlocals = _nlocals;
1407 nenums = _nenums;
1408 ntypedefs = _ntypedefs;
1409 nstructs = _nstructs;
1410 nfuncs = _nfuncs;
1411 narrays = _narrays;
1412 nglobals = _nglobals;
1413 return;
1415 if (!readdefs(localdef, NULL)) {
1416 tok_expect(';');
1417 return;
1419 if (!tok_jmp(TOK_TYPEDEF)) {
1420 readdefs(typedefdef, NULL);
1421 tok_expect(';');
1422 return;
1424 if (!tok_jmp(TOK_IF)) {
1425 long l1, l2;
1426 tok_expect('(');
1427 readexpr();
1428 tok_expect(')');
1429 ts_pop_de(NULL);
1430 l1 = o_jz(0);
1431 readstmt();
1432 if (!tok_jmp(TOK_ELSE)) {
1433 l2 = o_jmp(0);
1434 o_filljmp(l1);
1435 readstmt();
1436 o_filljmp(l2);
1437 } else {
1438 o_filljmp(l1);
1440 return;
1442 if (!tok_jmp(TOK_WHILE)) {
1443 long l1, l2;
1444 int break_beg = nbreaks;
1445 int continue_beg = ncontinues;
1446 l1 = o_mklabel();
1447 tok_expect('(');
1448 readexpr();
1449 tok_expect(')');
1450 ts_pop_de(NULL);
1451 l2 = o_jz(0);
1452 readstmt();
1453 o_jmp(l1);
1454 o_filljmp(l2);
1455 break_fill(o_mklabel(), break_beg);
1456 continue_fill(l1, continue_beg);
1457 return;
1459 if (!tok_jmp(TOK_DO)) {
1460 long l1, l2;
1461 int break_beg = nbreaks;
1462 int continue_beg = ncontinues;
1463 l1 = o_mklabel();
1464 readstmt();
1465 tok_expect(TOK_WHILE);
1466 tok_expect('(');
1467 l2 = o_mklabel();
1468 readexpr();
1469 ts_pop_de(NULL);
1470 o_jnz(l1);
1471 tok_expect(')');
1472 break_fill(o_mklabel(), break_beg);
1473 continue_fill(l2, continue_beg);
1474 tok_expect(';');
1475 return;
1477 if (!tok_jmp(TOK_FOR)) {
1478 long l_check, l_jump, j_fail, j_pass;
1479 int break_beg = nbreaks;
1480 int continue_beg = ncontinues;
1481 int has_cond = 0;
1482 tok_expect('(');
1483 if (tok_see() != ';')
1484 readestmt();
1485 tok_expect(';');
1486 l_check = o_mklabel();
1487 if (tok_see() != ';') {
1488 readestmt();
1489 ts_pop_de(NULL);
1490 j_fail = o_jz(0);
1491 has_cond = 1;
1493 tok_expect(';');
1494 j_pass = o_jmp(0);
1495 l_jump = o_mklabel();
1496 if (tok_see() != ')')
1497 readestmt();
1498 tok_expect(')');
1499 o_jmp(l_check);
1500 o_filljmp(j_pass);
1501 readstmt();
1502 o_jmp(l_jump);
1503 if (has_cond)
1504 o_filljmp(j_fail);
1505 break_fill(o_mklabel(), break_beg);
1506 continue_fill(l_jump, continue_beg);
1507 return;
1509 if (!tok_jmp(TOK_SWITCH)) {
1510 readswitch();
1511 return;
1513 if (!tok_jmp(TOK_RETURN)) {
1514 int ret = tok_see() != ';';
1515 if (ret) {
1516 readexpr();
1517 ts_pop_de(NULL);
1519 tok_expect(';');
1520 o_ret(ret);
1521 return;
1523 if (!tok_jmp(TOK_BREAK)) {
1524 tok_expect(';');
1525 breaks[nbreaks++] = o_jmp(0);
1526 return;
1528 if (!tok_jmp(TOK_CONTINUE)) {
1529 tok_expect(';');
1530 continues[ncontinues++] = o_jmp(0);
1531 return;
1533 if (!tok_jmp(TOK_GOTO)) {
1534 tok_expect(TOK_NAME);
1535 goto_add(tok_id());
1536 tok_expect(';');
1537 return;
1539 readestmt();
1540 /* labels */
1541 if (!tok_jmp(':')) {
1542 label_add(tok_id());
1543 return;
1545 tok_expect(';');
1548 static void readfunc(struct name *name, int flags)
1550 struct funcinfo *fi = &funcs[name->type.id];
1551 int i;
1552 strcpy(func_name, fi->name);
1553 o_func_beg(func_name, fi->nargs, F_GLOBAL(flags), fi->varg);
1554 for (i = 0; i < fi->nargs; i++) {
1555 struct name arg = {"", "", fi->args[i], o_arg2loc(i)};
1556 strcpy(arg.name, fi->argnames[i]);
1557 local_add(&arg);
1559 readstmt();
1560 goto_fill();
1561 o_func_end();
1562 func_name[0] = '\0';
1563 nlocals = 0;
1564 ngotos = 0;
1565 nlabels = 0;
1568 static void readdecl(void)
1570 if (!tok_jmp(TOK_TYPEDEF)) {
1571 readdefs(typedefdef, NULL);
1572 tok_expect(';');
1573 return;
1575 readdefs_int(globaldef, NULL);
1576 tok_jmp(';');
1579 static void parse(void)
1581 while (tok_see() != TOK_EOF)
1582 readdecl();
1585 static void compat_macros(void)
1587 cpp_define("__STDC__", "");
1588 cpp_define("__linux__", "");
1589 #ifdef NEATCC_ARM
1590 cpp_define("__arm__", "");
1591 #else
1592 cpp_define("__i386__", "");
1593 #endif
1595 /* ignored keywords */
1596 cpp_define("const", "");
1597 cpp_define("register", "");
1598 cpp_define("volatile", "");
1599 cpp_define("inline", "");
1600 cpp_define("restrict", "");
1601 cpp_define("__inline__", "");
1602 cpp_define("__restrict__", "");
1603 cpp_define("__attribute__(x)", "");
1604 cpp_define("__builtin_va_list__", "long");
1607 int main(int argc, char *argv[])
1609 char obj[128] = "";
1610 int ofd;
1611 int i = 1;
1612 compat_macros();
1613 while (i < argc && argv[i][0] == '-') {
1614 if (argv[i][1] == 'I')
1615 cpp_addpath(argv[i][2] ? argv[i] + 2 : argv[++i]);
1616 if (argv[i][1] == 'D') {
1617 char *name = argv[i] + 2;
1618 char *def = "";
1619 char *eq = strchr(name, '=');
1620 if (eq) {
1621 *eq = '\0';
1622 def = eq + 1;
1624 cpp_define(name, def);
1626 if (argv[i][1] == 'o')
1627 strcpy(obj, argv[i][2] ? argv[i] + 2 : argv[++i]);
1628 i++;
1630 if (i == argc)
1631 die("neatcc: no file given\n");
1632 if (cpp_init(argv[i]))
1633 die("neatcc: cannot open <%s>\n", argv[i]);
1634 parse();
1635 if (!*obj) {
1636 strcpy(obj, argv[i]);
1637 obj[strlen(obj) - 1] = 'o';
1639 ofd = open(obj, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1640 o_write(ofd);
1641 close(ofd);
1642 return 0;
1646 /* parsing function and variable declarations */
1648 /* read the base type of a variable */
1649 static int basetype(struct type *type, unsigned *flags)
1651 int sign = 1;
1652 int size = 4;
1653 int done = 0;
1654 int i = 0;
1655 int isunion;
1656 char name[NAMELEN] = "";
1657 *flags = 0;
1658 type->flags = 0;
1659 type->ptr = 0;
1660 type->addr = 0;
1661 while (!done) {
1662 switch (tok_see()) {
1663 case TOK_STATIC:
1664 *flags |= F_STATIC;
1665 break;
1666 case TOK_EXTERN:
1667 *flags |= F_EXTERN;
1668 break;
1669 case TOK_VOID:
1670 sign = 0;
1671 size = 0;
1672 done = 1;
1673 break;
1674 case TOK_INT:
1675 done = 1;
1676 break;
1677 case TOK_CHAR:
1678 size = 1;
1679 done = 1;
1680 break;
1681 case TOK_SHORT:
1682 size = 2;
1683 break;
1684 case TOK_LONG:
1685 size = LONGSZ;
1686 break;
1687 case TOK_SIGNED:
1688 break;
1689 case TOK_UNSIGNED:
1690 sign = 0;
1691 break;
1692 case TOK_UNION:
1693 case TOK_STRUCT:
1694 isunion = tok_get() == TOK_UNION;
1695 if (!tok_jmp(TOK_NAME))
1696 strcpy(name, tok_id());
1697 if (tok_see() == '{')
1698 type->id = struct_create(name, isunion);
1699 else
1700 type->id = struct_find(name, isunion);
1701 type->flags |= T_STRUCT;
1702 type->bt = LONGSZ;
1703 return 0;
1704 case TOK_ENUM:
1705 tok_get();
1706 tok_jmp(TOK_NAME);
1707 if (tok_see() == '{')
1708 enum_create();
1709 type->bt = 4 | BT_SIGNED;
1710 return 0;
1711 default:
1712 if (tok_see() == TOK_NAME) {
1713 int id = typedef_find(tok_id());
1714 if (id != -1) {
1715 tok_get();
1716 memcpy(type, &typedefs[id].type,
1717 sizeof(*type));
1718 return 0;
1721 if (!i)
1722 return 1;
1723 done = 1;
1724 continue;
1726 i++;
1727 tok_get();
1729 type->bt = size | (sign ? BT_SIGNED : 0);
1730 return 0;
1733 static void readptrs(struct type *type)
1735 while (!tok_jmp('*')) {
1736 type->ptr++;
1737 if (!type->bt)
1738 type->bt = 1;
1742 /* read function arguments */
1743 static int readargs(struct type *args, char argnames[][NAMELEN], int *varg)
1745 int nargs = 0;
1746 tok_expect('(');
1747 *varg = 0;
1748 while (tok_see() != ')') {
1749 if (!tok_jmp(TOK3("..."))) {
1750 *varg = 1;
1751 break;
1753 if (readname(&args[nargs], argnames[nargs], NULL)) {
1754 /* argument has no type, assume int */
1755 tok_expect(TOK_NAME);
1756 memset(&args[nargs], 0, sizeof(struct type));
1757 args[nargs].bt = 4 | BT_SIGNED;
1758 strcpy(argnames[nargs], tok_id());
1760 /* argument arrays are pointers */
1761 array2ptr(&args[nargs]);
1762 nargs++;
1763 if (tok_jmp(','))
1764 break;
1766 tok_expect(')');
1767 /* void argument */
1768 if (nargs == 1 && !TYPE_BT(&args[0]))
1769 return 0;
1770 return nargs;
1774 * readarrays() parses array specifiers when reading a definition in
1775 * readname(). The "type" parameter contains the type contained in the
1776 * inner array; for instance, type in "int *a[10][20]" would be an int
1777 * pointer. When returning, the "type" parameter is changed to point
1778 * to the final array. The function returns a pointer to the type in
1779 * the inner array; this is useful when the type is not complete yet,
1780 * like when creating an array of function pointers as in
1781 * "int (*f[10])(int)". If there is no array brackets, NULL is returned.
1783 static struct type *readarrays(struct type *type)
1785 long arsz[16];
1786 struct type *inner = NULL;
1787 int nar = 0;
1788 int i;
1789 while (!tok_jmp('[')) {
1790 long n = 0;
1791 if (tok_jmp(']')) {
1792 readexpr();
1793 ts_pop_de(NULL);
1794 if (o_popnum(&n))
1795 err("const expr expected\n");
1796 tok_expect(']');
1798 arsz[nar++] = n;
1800 for (i = nar - 1; i >= 0; i--) {
1801 type->id = array_add(type, arsz[i]);
1802 if (!inner)
1803 inner = &arrays[type->id].type;
1804 type->flags = T_ARRAY;
1805 type->bt = LONGSZ;
1806 type->ptr = 0;
1808 return inner;
1812 * readname() reads a variable definition; the name is copied into
1813 * "name" and the type is copied into "main" argument. The "base"
1814 * argument, if not NULL, indicates the base type of the variable.
1815 * For instance, the base type of "a" and "b" in "int *a, b[10]" is
1816 * "int". If NULL, basetype() is called directly to read the base
1817 * type of the variable. readname() returns zero, only if the
1818 * variable can be read.
1820 static int readname(struct type *main, char *name, struct type *base)
1822 struct type tpool[3];
1823 int npool = 0;
1824 struct type *type = &tpool[npool++];
1825 struct type *ptype = NULL; /* type inside parenthesis */
1826 struct type *btype = NULL; /* type before parenthesis */
1827 struct type *inner;
1828 unsigned flags;
1829 memset(tpool, 0, sizeof(tpool));
1830 if (name)
1831 *name = '\0';
1832 if (!base) {
1833 if (basetype(type, &flags))
1834 return 1;
1835 } else {
1836 memcpy(type, base, sizeof(*base));
1838 readptrs(type);
1839 if (!tok_jmp('(')) {
1840 btype = type;
1841 type = &tpool[npool++];
1842 ptype = type;
1843 readptrs(type);
1845 if (!tok_jmp(TOK_NAME) && name)
1846 strcpy(name, tok_id());
1847 inner = readarrays(type);
1848 if (ptype && inner)
1849 ptype = inner;
1850 if (ptype)
1851 tok_expect(')');
1852 if (tok_see() == '(') {
1853 struct type args[MAXARGS];
1854 char argnames[MAXARGS][NAMELEN];
1855 int varg = 0;
1856 int nargs = readargs(args, argnames, &varg);
1857 if (!ptype) {
1858 btype = type;
1859 type = &tpool[npool++];
1860 ptype = type;
1862 ptype->flags = T_FUNC;
1863 ptype->bt = LONGSZ;
1864 ptype->id = func_create(btype, name, argnames, args, nargs, varg);
1865 if (tok_see() != ';')
1866 while (tok_see() != '{' && !readdefs(krdef, &funcs[ptype->id]))
1867 tok_expect(';');
1868 } else {
1869 if (ptype && readarrays(type))
1870 array2ptr(type);
1872 memcpy(main, type, sizeof(*type));
1873 return 0;
1876 static int readtype(struct type *type)
1878 return readname(type, NULL, NULL);
1882 * readdef() reads a variable definitions statement. The definition
1883 * statement can appear in anywhere: global variables, function
1884 * local variables, struct fields, and typedefs. For each defined
1885 * variable, def() callback is called with the appropriate name
1886 * struct and flags; the callback should finish parsing the definition
1887 * by possibly reading the initializer expression and saving the name
1888 * struct.
1890 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
1891 void *data)
1893 struct type base;
1894 unsigned base_flags;
1895 if (basetype(&base, &base_flags))
1896 return 1;
1897 if (tok_see() == ';' || tok_see() == '{')
1898 return 0;
1899 do {
1900 struct name name = {{""}};
1901 if (readname(&name.type, name.name, &base))
1902 break;
1903 def(data, &name, base_flags);
1904 } while (!tok_jmp(','));
1905 return 0;
1908 /* just like readdefs, but default to int type; for handling K&R functions */
1909 static int readdefs_int(void (*def)(void *data, struct name *name, unsigned flags),
1910 void *data)
1912 struct type base;
1913 unsigned flags = 0;
1914 if (basetype(&base, &flags)) {
1915 if (tok_see() != TOK_NAME)
1916 return 1;
1917 memset(&base, 0, sizeof(base));
1918 base.bt = 4 | BT_SIGNED;
1920 if (tok_see() != ';') {
1921 do {
1922 struct name name = {{""}};
1923 if (readname(&name.type, name.name, &base))
1924 break;
1925 def(data, &name, flags);
1926 } while (!tok_jmp(','));
1928 return 0;
1932 /* parsing initializer expressions */
1934 static void jumpbrace(void)
1936 int depth = 0;
1937 while (tok_see() != '}' || depth--)
1938 if (tok_get() == '{')
1939 depth++;
1940 tok_expect('}');
1943 /* compute the size of the initializer expression */
1944 static int initsize(void)
1946 long addr = tok_addr();
1947 int n = 0;
1948 if (tok_jmp('='))
1949 err("array size unspecified");
1950 if (!tok_jmp(TOK_STR)) {
1951 n = tok_str(NULL);
1952 tok_jump(addr);
1953 return n;
1955 tok_expect('{');
1956 while (tok_jmp('}')) {
1957 long idx = n;
1958 if (!tok_jmp('[')) {
1959 readexpr();
1960 ts_pop_de(NULL);
1961 o_popnum(&idx);
1962 tok_expect(']');
1963 tok_expect('=');
1965 if (n < idx + 1)
1966 n = idx + 1;
1967 while (tok_see() != '}' && tok_see() != ',')
1968 if (tok_get() == '{')
1969 jumpbrace();
1970 tok_jmp(',');
1972 tok_jump(addr);
1973 return n;
1976 static struct type *innertype(struct type *t)
1978 if (t->flags & T_ARRAY && !t->ptr)
1979 return innertype(&arrays[t->id].type);
1980 return t;
1983 /* read the initializer expression and initialize basic types using set() cb */
1984 static void initexpr(struct type *t, int off, void *obj,
1985 void (*set)(void *obj, int off, struct type *t))
1987 if (tok_jmp('{')) {
1988 set(obj, off, t);
1989 return;
1991 if (!t->ptr && t->flags & T_STRUCT) {
1992 struct structinfo *si = &structs[t->id];
1993 int i;
1994 for (i = 0; i < si->nfields && tok_see() != '}'; i++) {
1995 struct name *field = &si->fields[i];
1996 if (!tok_jmp('.')) {
1997 tok_expect(TOK_NAME);
1998 field = struct_field(t->id, tok_id());
1999 tok_expect('=');
2001 initexpr(&field->type, off + field->addr, obj, set);
2002 if (tok_jmp(','))
2003 break;
2005 } else if (t->flags & T_ARRAY) {
2006 struct type *t_de = &arrays[t->id].type;
2007 int i;
2008 /* handling extra braces as in: char s[] = {"sth"} */
2009 if (TYPE_SZ(t_de) == 1 && tok_see() == TOK_STR) {
2010 set(obj, off, t);
2011 tok_expect('}');
2012 return;
2014 for (i = 0; tok_see() != '}'; i++) {
2015 long idx = i;
2016 struct type *it = t_de;
2017 if (!tok_jmp('[')) {
2018 readexpr();
2019 ts_pop_de(NULL);
2020 o_popnum(&idx);
2021 tok_expect(']');
2022 tok_expect('=');
2024 if (tok_see() != '{' && (tok_see() != TOK_STR ||
2025 !(it->flags & T_ARRAY)))
2026 it = innertype(t_de);
2027 initexpr(it, off + type_totsz(it) * idx, obj, set);
2028 if (tok_jmp(','))
2029 break;
2032 tok_expect('}');