file move
[neatcc/cc.git] / ncc.c
blob9fefeb9ccfa7347a849de9d8d3f06200db47caa1
1 /*
2 * neatcc - the neatcc compiler
4 * Copyright (C) 2010-2015 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))
64 #define MAX(a, b) ((a) < (b) ? (b) : (a))
66 #define TYPE_BT(t) ((t)->ptr ? LONGSZ : (t)->bt)
67 #define TYPE_SZ(t) ((t)->ptr ? LONGSZ : (t)->bt & BT_SZMASK)
68 #define TYPE_VOID(t) (!(t)->bt && !(t)->flags && !(t)->ptr)
70 /* type->flag values */
71 #define T_ARRAY 0x01
72 #define T_STRUCT 0x02
73 #define T_FUNC 0x04
75 /* variable definition flags */
76 #define F_STATIC 0x01
77 #define F_EXTERN 0x02
79 struct type {
80 unsigned bt;
81 unsigned flags;
82 int ptr;
83 int id; /* for structs, functions and arrays */
84 int addr; /* the address is passed to gen.c; deref for value */
87 /* type stack */
88 static struct type ts[NTMPS];
89 static int nts;
91 static void ts_push_bt(unsigned bt)
93 ts[nts].ptr = 0;
94 ts[nts].flags = 0;
95 ts[nts].addr = 0;
96 ts[nts++].bt = bt;
97 #ifdef NCCWORDCAST
98 o_cast(bt); /* casting to architecture word */
99 #endif
102 static void ts_push(struct type *t)
104 struct type *d = &ts[nts++];
105 memcpy(d, t, sizeof(*t));
108 static void ts_push_addr(struct type *t)
110 ts_push(t);
111 ts[nts - 1].addr = 1;
114 static void ts_pop(struct type *type)
116 nts--;
117 if (type)
118 *type = ts[nts];
121 void err(char *fmt, ...)
123 va_list ap;
124 char msg[512];
125 va_start(ap, fmt);
126 vsprintf(msg, fmt, ap);
127 va_end(ap);
128 die("%s: %s", cpp_loc(tok_addr()), msg);
131 struct name {
132 char name[NAMELEN];
133 char elfname[NAMELEN]; /* local elf name for function static variables */
134 struct type type;
135 long addr; /* local stack offset, global data addr, struct offset */
138 static struct name locals[NLOCALS];
139 static int nlocals;
140 static struct name globals[NGLOBALS];
141 static int nglobals;
143 static void local_add(struct name *name)
145 if (nlocals >= NLOCALS)
146 err("nomem: NLOCALS reached!\n");
147 memcpy(&locals[nlocals++], name, sizeof(*name));
150 static int local_find(char *name)
152 int i;
153 for (i = nlocals - 1; i >= 0; --i)
154 if (!strcmp(locals[i].name, name))
155 return i;
156 return -1;
159 static int global_find(char *name)
161 int i;
162 for (i = nglobals - 1; i >= 0; i--)
163 if (!strcmp(name, globals[i].name))
164 return i;
165 return -1;
168 static void global_add(struct name *name)
170 if (nglobals >= NGLOBALS)
171 err("nomem: NGLOBALS reached!\n");
172 memcpy(&globals[nglobals++], name, sizeof(*name));
175 #define LABEL() (++label)
177 static int label; /* last used label id */
178 static int l_break; /* current break label */
179 static int l_cont; /* current continue label */
181 static struct enumval {
182 char name[NAMELEN];
183 int n;
184 } enums[NENUMS];
185 static int nenums;
187 static void enum_add(char *name, int val)
189 struct enumval *ev = &enums[nenums++];
190 if (nenums >= NENUMS)
191 err("nomem: NENUMS reached!\n");
192 strcpy(ev->name, name);
193 ev->n = val;
196 static int enum_find(int *val, char *name)
198 int i;
199 for (i = nenums - 1; i >= 0; --i)
200 if (!strcmp(name, enums[i].name)) {
201 *val = enums[i].n;
202 return 0;
204 return 1;
207 static struct typdefinfo {
208 char name[NAMELEN];
209 struct type type;
210 } typedefs[NTYPEDEFS];
211 static int ntypedefs;
213 static void typedef_add(char *name, struct type *type)
215 struct typdefinfo *ti = &typedefs[ntypedefs++];
216 if (ntypedefs >= NTYPEDEFS)
217 err("nomem: NTYPEDEFS reached!\n");
218 strcpy(ti->name, name);
219 memcpy(&ti->type, type, sizeof(*type));
222 static int typedef_find(char *name)
224 int i;
225 for (i = ntypedefs - 1; i >= 0; --i)
226 if (!strcmp(name, typedefs[i].name))
227 return i;
228 return -1;
231 static struct array {
232 struct type type;
233 int n;
234 } arrays[NARRAYS];
235 static int narrays;
237 static int array_add(struct type *type, int n)
239 struct array *a = &arrays[narrays++];
240 if (narrays >= NARRAYS)
241 err("nomem: NARRAYS reached!\n");
242 memcpy(&a->type, type, sizeof(*type));
243 a->n = n;
244 return a - arrays;
247 static void array2ptr(struct type *t)
249 if (t->flags & T_ARRAY && !t->ptr) {
250 memcpy(t, &arrays[t->id].type, sizeof(*t));
251 t->ptr++;
255 static struct structinfo {
256 char name[NAMELEN];
257 struct name fields[NFIELDS];
258 int nfields;
259 int isunion;
260 int size;
261 } structs[NSTRUCTS];
262 static int nstructs;
264 static int struct_find(char *name, int isunion)
266 int i;
267 for (i = nstructs - 1; i >= 0; --i)
268 if (*structs[i].name && !strcmp(name, structs[i].name) &&
269 structs[i].isunion == isunion)
270 return i;
271 i = nstructs++;
272 if (nstructs >= NSTRUCTS)
273 err("nomem: NSTRUCTS reached!\n");
274 memset(&structs[i], 0, sizeof(structs[i]));
275 strcpy(structs[i].name, name);
276 structs[i].isunion = isunion;
277 return i;
280 static struct name *struct_field(int id, char *name)
282 struct structinfo *si = &structs[id];
283 int i;
284 for (i = 0; i < si->nfields; i++)
285 if (!strcmp(name, si->fields[i].name))
286 return &si->fields[i];
287 err("field not found\n");
288 return NULL;
291 /* return t's size */
292 static int type_totsz(struct type *t)
294 if (t->ptr)
295 return LONGSZ;
296 if (t->flags & T_ARRAY)
297 return arrays[t->id].n * type_totsz(&arrays[t->id].type);
298 return t->flags & T_STRUCT ? structs[t->id].size : BT_SZ(t->bt);
301 /* return t's dereferenced size */
302 static unsigned type_szde(struct type *t)
304 struct type de = *t;
305 array2ptr(&de);
306 de.ptr--;
307 return type_totsz(&de);
310 /* dereference stack top if t->addr (ie. address is pushed to gen.c) */
311 static void ts_de(int deref)
313 struct type *t = &ts[nts - 1];
314 array2ptr(t);
315 if (deref && t->addr && (t->ptr || !(t->flags & T_FUNC)))
316 o_deref(TYPE_BT(t));
317 t->addr = 0;
320 /* pop stack pop to *t and dereference if t->addr */
321 static void ts_pop_de(struct type *t)
323 ts_de(1);
324 ts_pop(t);
327 /* pop the top 2 stack values and dereference them if t->addr */
328 static void ts_pop_de2(struct type *t1, struct type *t2)
330 ts_pop_de(t1);
331 o_tmpswap();
332 ts_pop_de(t2);
333 o_tmpswap();
336 static int tok_jmp(int tok)
338 if (tok_see() != tok)
339 return 1;
340 tok_get();
341 return 0;
344 static void tok_expect(int tok)
346 if (tok_get() != tok)
347 err("syntax error\n");
350 /* the result of a binary operation on variables of type bt1 and bt2 */
351 static unsigned bt_op(unsigned bt1, unsigned bt2)
353 int sz = MAX(BT_SZ(bt1), BT_SZ(bt2));
354 return ((bt1 | bt2) & BT_SIGNED) | MAX(sz, 4);
357 /* the result of a unary operation on variables of bt */
358 static unsigned bt_uop(unsigned bt)
360 return bt_op(bt, 4);
363 /* push the result of a binary operation on the type stack */
364 static void ts_binop(int op)
366 struct type t1, t2;
367 unsigned bt1, bt2, bt;
368 ts_pop_de2(&t1, &t2);
369 bt1 = TYPE_BT(&t1);
370 bt2 = TYPE_BT(&t2);
371 bt = bt_op(bt1, bt2);
372 if (op == O_DIV || op == O_MOD)
373 bt = BT(bt2 & BT_SIGNED, bt);
374 o_bop(op | (bt & BT_SIGNED ? O_SIGNED : 0));
375 ts_push_bt(bt);
378 /* push the result of an additive binary operation on the type stack */
379 static void ts_addop(int op)
381 struct type t1, t2;
382 ts_pop_de2(&t1, &t2);
383 if (!t1.ptr && !t2.ptr) {
384 o_bop(op);
385 ts_push_bt(bt_op(TYPE_BT(&t1), TYPE_BT(&t2)));
386 return;
388 if (t1.ptr && !t2.ptr)
389 o_tmpswap();
390 if (!t1.ptr && t2.ptr)
391 if (type_szde(&t2) > 1) {
392 o_num(type_szde(&t2));
393 o_bop(O_MUL);
395 if (t1.ptr && !t2.ptr)
396 o_tmpswap();
397 o_bop(op);
398 if (t1.ptr && t2.ptr) {
399 int sz = type_szde(&t1);
400 if (sz > 1) {
401 o_num(sz);
402 o_bop(O_DIV);
404 ts_push_bt(LONGSZ | BT_SIGNED);
405 } else {
406 ts_push(t1.ptr ? &t1 : &t2);
410 /* function prototypes for parsing function and variable declarations */
411 static int readname(struct type *main, char *name, struct type *base);
412 static int readtype(struct type *type);
413 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
414 void *data);
415 static int readdefs_int(void (*def)(void *data, struct name *name, unsigned flags),
416 void *data);
418 /* function prototypes for parsing initializer expressions */
419 static int initsize(void);
420 static void initexpr(struct type *t, int off, void *obj,
421 void (*set)(void *obj, int off, struct type *t));
423 static int type_alignment(struct type *t)
425 if (t->flags & T_ARRAY && !t->ptr)
426 return type_alignment(&arrays[t->id].type);
427 if (t->flags & T_STRUCT && !t->ptr)
428 return type_alignment(&structs[t->id].fields[0].type);
429 return MIN(LONGSZ, type_totsz(t));
432 static void structdef(void *data, struct name *name, unsigned flags)
434 struct structinfo *si = data;
435 if (si->isunion) {
436 name->addr = 0;
437 if (si->size < type_totsz(&name->type))
438 si->size = type_totsz(&name->type);
439 } else {
440 struct type *t = &name->type;
441 int alignment = type_alignment(t);
442 if (t->flags & T_ARRAY && !t->ptr)
443 alignment = MIN(LONGSZ, type_totsz(&arrays[t->id].type));
444 si->size = ALIGN(si->size, alignment);
445 name->addr = si->size;
446 si->size += type_totsz(&name->type);
448 memcpy(&si->fields[si->nfields++], name, sizeof(*name));
451 static int struct_create(char *name, int isunion)
453 int id = struct_find(name, isunion);
454 struct structinfo *si = &structs[id];
455 tok_expect('{');
456 while (tok_jmp('}')) {
457 readdefs(structdef, si);
458 tok_expect(';');
460 return id;
463 static void readexpr(void);
465 static void enum_create(void)
467 long n = 0;
468 tok_expect('{');
469 while (tok_jmp('}')) {
470 char name[NAMELEN];
471 tok_expect(TOK_NAME);
472 strcpy(name, tok_id());
473 if (!tok_jmp('=')) {
474 readexpr();
475 ts_pop_de(NULL);
476 if (o_popnum(&n))
477 err("const expr expected!\n");
479 enum_add(name, n++);
480 tok_jmp(',');
484 /* used to differentiate labels from case and cond exprs */
485 static int ncexpr;
486 static int caseexpr;
488 static void readpre(void);
490 static char *tmp_str(char *buf, int len)
492 static char name[NAMELEN];
493 static int id;
494 sprintf(name, "__neatcc.s%d", id++);
495 o_dscpy(o_dsnew(name, len, 0), buf, len);
496 return name;
499 static void readprimary(void)
501 if (!tok_jmp(TOK_NUM)) {
502 long n;
503 int bt = tok_num(&n);
504 o_num(n);
505 ts_push_bt(bt);
506 return;
508 if (!tok_jmp(TOK_STR)) {
509 struct type t = {}; /* char type inside the arrays */
510 struct type a = {}; /* the char array type */
511 char *buf;
512 int len;
513 tok_str(&buf, &len);
514 t.bt = 1 | BT_SIGNED;
515 a.id = array_add(&t, len);
516 a.flags = T_ARRAY;
517 o_sym(tmp_str(buf, len));
518 ts_push(&a);
519 return;
521 if (!tok_jmp(TOK_NAME)) {
522 struct name unkn = {""};
523 char *name = unkn.name;
524 int n;
525 strcpy(name, tok_id());
526 /* don't search for labels here */
527 if (!ncexpr && !caseexpr && tok_see() == ':')
528 return;
529 if ((n = local_find(name)) != -1) {
530 struct name *l = &locals[n];
531 o_local(l->addr);
532 ts_push_addr(&l->type);
533 return;
535 if ((n = global_find(name)) != -1) {
536 struct name *g = &globals[n];
537 o_sym(*g->elfname ? g->elfname : g->name);
538 ts_push_addr(&g->type);
539 return;
541 if (!enum_find(&n, name)) {
542 o_num(n);
543 ts_push_bt(4 | BT_SIGNED);
544 return;
546 if (tok_see() != '(')
547 err("unknown symbol <%s>\n", name);
548 global_add(&unkn);
549 o_sym(unkn.name);
550 ts_push_bt(LONGSZ);
551 return;
553 if (!tok_jmp('(')) {
554 struct type t;
555 if (!readtype(&t)) {
556 struct type o;
557 tok_expect(')');
558 readpre();
559 ts_pop_de(&o);
560 ts_push(&t);
561 if (!t.ptr || !o.ptr)
562 o_cast(TYPE_BT(&t));
563 } else {
564 readexpr();
565 while (tok_jmp(')')) {
566 tok_expect(',');
567 ts_pop(NULL);
568 o_tmpdrop(1);
569 readexpr();
572 return;
576 static void arrayderef(void)
578 struct type t;
579 int sz;
580 ts_pop_de(NULL);
581 ts_pop(&t);
582 if (!(t.flags & T_ARRAY && !t.ptr) && t.addr) {
583 o_tmpswap();
584 o_deref(TYPE_BT(&t));
585 o_tmpswap();
587 array2ptr(&t);
588 t.ptr--;
589 sz = type_totsz(&t);
590 t.addr = 1;
591 if (sz > 1) {
592 o_num(sz);
593 o_bop(O_MUL);
595 o_bop(O_ADD);
596 ts_push(&t);
599 static void inc_post(int op)
601 struct type t = ts[nts - 1];
602 /* pushing the value before inc */
603 o_tmpcopy();
604 ts_de(1);
605 o_load();
606 o_tmpswap();
608 /* increment by 1 or pointer size */
609 o_tmpcopy();
610 ts_push(&t);
611 ts_pop_de(&t);
612 o_num(t.ptr > 0 ? type_szde(&t) : 1);
613 o_bop(op);
615 /* assign back */
616 o_assign(TYPE_BT(&t));
617 o_tmpdrop(1);
620 static void readfield(void)
622 struct name *field;
623 struct type t;
624 tok_expect(TOK_NAME);
625 ts_pop(&t);
626 array2ptr(&t);
627 field = struct_field(t.id, tok_id());
628 if (field->addr) {
629 o_num(field->addr);
630 o_bop(O_ADD);
632 ts_push_addr(&field->type);
635 static struct funcinfo {
636 struct type args[NARGS];
637 struct type ret;
638 int nargs;
639 int varg;
640 /* function and argument names; useful only when defining */
641 char argnames[NARGS][NAMELEN];
642 char name[NAMELEN];
643 } funcs[NFUNCS];
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 >= NFUNCS)
652 err("nomem: NFUNCS 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 ? 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 struct type t;
745 if (!tok_jmp('&')) {
746 readpre();
747 ts_pop(&t);
748 if (!t.addr)
749 err("cannot use the address\n");
750 t.ptr++;
751 t.addr = 0;
752 ts_push(&t);
753 return;
755 if (!tok_jmp('*')) {
756 readpre();
757 ts_pop(&t);
758 array2ptr(&t);
759 if (!t.ptr)
760 err("dereferencing non-pointer\n");
761 if (t.addr)
762 o_deref(TYPE_BT(&t));
763 t.ptr--;
764 t.addr = 1;
765 ts_push(&t);
766 return;
768 if (!tok_jmp('!')) {
769 readpre();
770 ts_pop_de(NULL);
771 o_uop(O_LNOT);
772 ts_push_bt(4 | BT_SIGNED);
773 return;
775 if (!tok_jmp('+')) {
776 readpre();
777 ts_de(1);
778 ts_pop(&t);
779 ts_push_bt(bt_uop(TYPE_BT(&t)));
780 return;
782 if (!tok_jmp('-')) {
783 readpre();
784 ts_de(1);
785 ts_pop(&t);
786 o_uop(O_NEG);
787 ts_push_bt(bt_uop(TYPE_BT(&t)));
788 return;
790 if (!tok_jmp('~')) {
791 readpre();
792 ts_de(1);
793 ts_pop(&t);
794 o_uop(O_NOT);
795 ts_push_bt(bt_uop(TYPE_BT(&t)));
796 return;
798 if (!tok_jmp(TOK2("++"))) {
799 inc_pre(O_ADD);
800 return;
802 if (!tok_jmp(TOK2("--"))) {
803 inc_pre(O_SUB);
804 return;
806 if (!tok_jmp(TOK_SIZEOF)) {
807 struct type t;
808 int op = !tok_jmp('(');
809 if (readtype(&t)) {
810 nogen++;
811 if (op)
812 readexpr();
813 else
814 readpre();
815 nogen--;
816 ts_pop(&t);
818 o_num(type_totsz(&t));
819 ts_push_bt(LONGSZ);
820 if (op)
821 tok_expect(')');
822 return;
824 readpost();
827 static void readmul(void)
829 readpre();
830 while (1) {
831 if (!tok_jmp('*')) {
832 readpre();
833 ts_binop(O_MUL);
834 continue;
836 if (!tok_jmp('/')) {
837 readpre();
838 ts_binop(O_DIV);
839 continue;
841 if (!tok_jmp('%')) {
842 readpre();
843 ts_binop(O_MOD);
844 continue;
846 break;
850 static void readadd(void)
852 readmul();
853 while (1) {
854 if (!tok_jmp('+')) {
855 readmul();
856 ts_addop(O_ADD);
857 continue;
859 if (!tok_jmp('-')) {
860 readmul();
861 ts_addop(O_SUB);
862 continue;
864 break;
868 static void shift(int op)
870 struct type t;
871 readadd();
872 ts_pop_de2(NULL, &t);
873 o_bop(op | (BT_SIGNED & TYPE_BT(&t) ? O_SIGNED : 0));
874 ts_push_bt(bt_uop(TYPE_BT(&t)));
877 static void readshift(void)
879 readadd();
880 while (1) {
881 if (!tok_jmp(TOK2("<<"))) {
882 shift(O_SHL);
883 continue;
885 if (!tok_jmp(TOK2(">>"))) {
886 shift(O_SHR);
887 continue;
889 break;
893 static void cmp(int op)
895 struct type t1, t2;
896 int bt;
897 readshift();
898 ts_pop_de2(&t1, &t2);
899 bt = bt_op(TYPE_BT(&t1), TYPE_BT(&t2));
900 o_bop(op | (bt & BT_SIGNED ? O_SIGNED : 0));
901 ts_push_bt(4 | BT_SIGNED);
904 static void readcmp(void)
906 readshift();
907 while (1) {
908 if (!tok_jmp('<')) {
909 cmp(O_LT);
910 continue;
912 if (!tok_jmp('>')) {
913 cmp(O_GT);
914 continue;
916 if (!tok_jmp(TOK2("<="))) {
917 cmp(O_LE);
918 continue;
920 if (!tok_jmp(TOK2(">="))) {
921 cmp(O_GE);
922 continue;
924 break;
928 static void eq(int op)
930 readcmp();
931 ts_pop_de2(NULL, NULL);
932 o_bop(op);
933 ts_push_bt(4 | BT_SIGNED);
936 static void readeq(void)
938 readcmp();
939 while (1) {
940 if (!tok_jmp(TOK2("=="))) {
941 eq(O_EQ);
942 continue;
944 if (!tok_jmp(TOK2("!="))) {
945 eq(O_NEQ);
946 continue;
948 break;
952 static void readbitand(void)
954 readeq();
955 while (!tok_jmp('&')) {
956 readeq();
957 ts_binop(O_AND);
961 static void readxor(void)
963 readbitand();
964 while (!tok_jmp('^')) {
965 readbitand();
966 ts_binop(O_XOR);
970 static void readbitor(void)
972 readxor();
973 while (!tok_jmp('|')) {
974 readxor();
975 ts_binop(O_OR);
979 static void readand(void)
981 int l_out, l_fail;
982 readbitor();
983 if (tok_see() != TOK2("&&"))
984 return;
985 l_out = LABEL();
986 l_fail = LABEL();
987 o_fork();
988 ts_pop_de(NULL);
989 o_jz(l_fail);
990 while (!tok_jmp(TOK2("&&"))) {
991 readbitor();
992 ts_pop_de(NULL);
993 o_jz(l_fail);
995 o_num(1);
996 o_forkpush();
997 o_jmp(l_out);
998 o_label(l_fail);
999 o_num(0);
1000 o_forkpush();
1001 o_forkjoin();
1002 o_label(l_out);
1003 ts_push_bt(4 | BT_SIGNED);
1006 static void reador(void)
1008 int l_pass, l_end;
1009 readand();
1010 if (tok_see() != TOK2("||"))
1011 return;
1012 l_pass = LABEL();
1013 l_end = LABEL();
1014 o_fork();
1015 ts_pop_de(NULL);
1016 o_jnz(l_pass);
1017 while (!tok_jmp(TOK2("||"))) {
1018 readand();
1019 ts_pop_de(NULL);
1020 o_jnz(l_pass);
1022 o_num(0);
1023 o_forkpush();
1024 o_jmp(l_end);
1025 o_label(l_pass);
1026 o_num(1);
1027 o_forkpush();
1028 o_forkjoin();
1029 o_label(l_end);
1030 ts_push_bt(4 | BT_SIGNED);
1033 static void readcexpr(void);
1035 static int readcexpr_const(void)
1037 long c;
1038 if (o_popnum(&c))
1039 return -1;
1040 if (!c)
1041 nogen++;
1042 readcexpr();
1043 /* both branches yield the same type; so ignore the first */
1044 ts_pop_de(NULL);
1045 tok_expect(':');
1046 if (c)
1047 nogen++;
1048 else
1049 nogen--;
1050 readcexpr();
1051 /* making sure t->addr == 0 on both branches */
1052 ts_de(1);
1053 if (c)
1054 nogen--;
1055 return 0;
1058 static void readcexpr(void)
1060 reador();
1061 if (tok_jmp('?'))
1062 return;
1063 ncexpr++;
1064 ts_pop_de(NULL);
1065 o_fork();
1066 if (readcexpr_const()) {
1067 int l_fail = LABEL();
1068 int l_end = LABEL();
1069 struct type ret;
1070 o_jz(l_fail);
1071 readcexpr();
1072 /* both branches yield the same type; so ignore the first */
1073 ts_pop_de(&ret);
1074 if (!TYPE_VOID(&ret))
1075 o_forkpush();
1076 o_jmp(l_end);
1078 tok_expect(':');
1079 o_label(l_fail);
1080 readcexpr();
1081 /* making sure t->addr == 0 on both branches */
1082 ts_de(1);
1083 if (!TYPE_VOID(&ret)) {
1084 o_forkpush();
1085 o_forkjoin();
1087 o_label(l_end);
1089 ncexpr--;
1092 static void opassign(int op, int ptrop)
1094 struct type t = ts[nts - 1];
1095 o_tmpcopy();
1096 ts_push(&t);
1097 readexpr();
1098 if (op == O_ADD || op == O_SUB)
1099 ts_addop(op);
1100 else
1101 ts_binop(op);
1102 o_assign(TYPE_BT(&ts[nts - 2]));
1103 ts_pop(NULL);
1104 ts_de(0);
1107 static void doassign(void)
1109 struct type t = ts[nts - 1];
1110 if (!t.ptr && t.flags & T_STRUCT) {
1111 ts_pop(NULL);
1112 o_num(type_totsz(&t));
1113 o_memcpy();
1114 } else {
1115 ts_pop_de(NULL);
1116 o_assign(TYPE_BT(&ts[nts - 1]));
1117 ts_de(0);
1121 static void readexpr(void)
1123 readcexpr();
1124 if (!tok_jmp('=')) {
1125 readexpr();
1126 doassign();
1127 return;
1129 if (!tok_jmp(TOK2("+="))) {
1130 opassign(O_ADD, 1);
1131 return;
1133 if (!tok_jmp(TOK2("-="))) {
1134 opassign(O_SUB, 1);
1135 return;
1137 if (!tok_jmp(TOK2("*="))) {
1138 opassign(O_MUL, 0);
1139 return;
1141 if (!tok_jmp(TOK2("/="))) {
1142 opassign(O_DIV, 0);
1143 return;
1145 if (!tok_jmp(TOK2("%="))) {
1146 opassign(O_MOD, 0);
1147 return;
1149 if (!tok_jmp(TOK3("<<="))) {
1150 opassign(O_SHL, 0);
1151 return;
1153 if (!tok_jmp(TOK3(">>="))) {
1154 opassign(O_SHR, 0);
1155 return;
1157 if (!tok_jmp(TOK3("&="))) {
1158 opassign(O_AND, 0);
1159 return;
1161 if (!tok_jmp(TOK3("|="))) {
1162 opassign(O_OR, 0);
1163 return;
1165 if (!tok_jmp(TOK3("^="))) {
1166 opassign(O_XOR, 0);
1167 return;
1171 static void readestmt(void)
1173 do {
1174 o_tmpdrop(-1);
1175 nts = 0;
1176 readexpr();
1177 } while (!tok_jmp(','));
1180 #define F_GLOBAL(flags) (!((flags) & F_STATIC))
1182 static void globalinit(void *obj, int off, struct type *t)
1184 struct name *name = obj;
1185 char *elfname = *name->elfname ? name->elfname : name->name;
1186 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1187 struct type *t_de = &arrays[t->id].type;
1188 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1189 char *buf;
1190 int len;
1191 tok_expect(TOK_STR);
1192 tok_str(&buf, &len);
1193 o_dscpy(name->addr + off, buf, len);
1194 return;
1197 readexpr();
1198 o_dsset(elfname, off, TYPE_BT(t));
1199 ts_pop(NULL);
1202 static void readfunc(struct name *name, int flags);
1204 static void globaldef(void *data, struct name *name, unsigned flags)
1206 struct type *t = &name->type;
1207 char *elfname = *name->elfname ? name->elfname : name->name;
1208 int sz;
1209 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1210 if (~flags & F_EXTERN)
1211 arrays[t->id].n = initsize();
1212 sz = type_totsz(t);
1213 if (!(flags & F_EXTERN) && (!(t->flags & T_FUNC) || t->ptr)) {
1214 if (tok_see() == '=')
1215 name->addr = o_dsnew(elfname, sz, F_GLOBAL(flags));
1216 else
1217 o_bsnew(elfname, sz, F_GLOBAL(flags));
1219 global_add(name);
1220 if (!tok_jmp('='))
1221 initexpr(t, 0, name, globalinit);
1222 if (tok_see() == '{' && name->type.flags & T_FUNC)
1223 readfunc(name, flags);
1226 /* generate the address of local + off */
1227 static void o_localoff(long addr, int off)
1229 o_local(addr);
1230 if (off) {
1231 o_num(off);
1232 o_bop(O_ADD);
1236 static void localinit(void *obj, int off, struct type *t)
1238 long addr = *(long *) obj;
1239 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1240 struct type *t_de = &arrays[t->id].type;
1241 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1242 char *buf;
1243 int len;
1244 tok_expect(TOK_STR);
1245 tok_str(&buf, &len);
1246 o_localoff(addr, off);
1247 o_sym(tmp_str(buf, len));
1248 o_num(len);
1249 o_memcpy();
1250 o_tmpdrop(1);
1251 return;
1254 o_localoff(addr, off);
1255 ts_push(t);
1256 readexpr();
1257 doassign();
1258 ts_pop(NULL);
1259 o_tmpdrop(1);
1262 /* current function name */
1263 static char func_name[NAMELEN];
1265 static void localdef(void *data, struct name *name, unsigned flags)
1267 struct type *t = &name->type;
1268 if ((flags & F_EXTERN) || ((t->flags & T_FUNC) && !t->ptr)) {
1269 global_add(name);
1270 return;
1272 if (flags & F_STATIC) {
1273 sprintf(name->elfname, "__neatcc.%s.%s", func_name, name->name);
1274 globaldef(data, name, flags);
1275 return;
1277 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1278 arrays[t->id].n = initsize();
1279 name->addr = o_mklocal(type_totsz(&name->type));
1280 local_add(name);
1281 if (!tok_jmp('=')) {
1282 if (t->flags & (T_ARRAY | T_STRUCT) && !t->ptr) {
1283 o_local(name->addr);
1284 o_num(0);
1285 o_num(type_totsz(t));
1286 o_memset();
1287 o_tmpdrop(1);
1289 initexpr(t, 0, &name->addr, localinit);
1293 static void typedefdef(void *data, struct name *name, unsigned flags)
1295 typedef_add(name->name, &name->type);
1298 static void readstmt(void);
1300 static void readswitch(void)
1302 int o_break = l_break;
1303 long val_addr = o_mklocal(LONGSZ);
1304 struct type t;
1305 int ncases = 0; /* number of case labels */
1306 int l_failed = LABEL(); /* address of last failed jmp */
1307 int l_matched = LABEL(); /* address of last walk through jmp */
1308 int l_default = 0; /* default case label */
1309 l_break = LABEL();
1310 tok_expect('(');
1311 readexpr();
1312 ts_pop_de(&t);
1313 o_local(val_addr);
1314 o_tmpswap();
1315 o_assign(TYPE_BT(&t));
1316 ts_de(0);
1317 o_tmpdrop(1);
1318 tok_expect(')');
1319 tok_expect('{');
1320 while (tok_jmp('}')) {
1321 if (tok_see() != TOK_CASE && tok_see() != TOK_DEFAULT) {
1322 readstmt();
1323 continue;
1325 if (ncases)
1326 o_jmp(l_matched);
1327 if (tok_get() == TOK_CASE) {
1328 o_label(l_failed);
1329 l_failed = LABEL();
1330 caseexpr = 1;
1331 readexpr();
1332 ts_pop_de(NULL);
1333 caseexpr = 0;
1334 o_local(val_addr);
1335 o_deref(TYPE_BT(&t));
1336 o_bop(O_EQ);
1337 o_jz(l_failed);
1338 o_tmpdrop(1);
1339 } else {
1340 if (!ncases)
1341 o_jmp(l_failed);
1342 l_default = LABEL();
1343 o_label(l_default);
1345 tok_expect(':');
1346 o_label(l_matched);
1347 l_matched = LABEL();
1348 ncases++;
1350 o_rmlocal(val_addr, LONGSZ);
1351 o_jmp(l_break);
1352 o_label(l_failed);
1353 if (l_default)
1354 o_jmp(l_default);
1355 o_label(l_break);
1356 l_break = o_break;
1359 static char label_name[NLABELS][NAMELEN];
1360 static int label_ids[NLABELS];
1361 static int nlabels;
1363 static int label_id(char *name)
1365 int i;
1366 for (i = nlabels - 1; i >= 0; --i)
1367 if (!strcmp(label_name[i], name))
1368 return label_ids[i];
1369 strcpy(label_name[nlabels], name);
1370 label_ids[nlabels] = LABEL();
1371 return label_ids[nlabels++];
1374 static void readstmt(void)
1376 o_tmpdrop(-1);
1377 nts = 0;
1378 if (!tok_jmp('{')) {
1379 int _nlocals = nlocals;
1380 int _nglobals = nglobals;
1381 int _nenums = nenums;
1382 int _ntypedefs = ntypedefs;
1383 int _nstructs = nstructs;
1384 int _nfuncs = nfuncs;
1385 int _narrays = narrays;
1386 while (tok_jmp('}'))
1387 readstmt();
1388 nlocals = _nlocals;
1389 nenums = _nenums;
1390 ntypedefs = _ntypedefs;
1391 nstructs = _nstructs;
1392 nfuncs = _nfuncs;
1393 narrays = _narrays;
1394 nglobals = _nglobals;
1395 return;
1397 if (!readdefs(localdef, NULL)) {
1398 tok_expect(';');
1399 return;
1401 if (!tok_jmp(TOK_TYPEDEF)) {
1402 readdefs(typedefdef, NULL);
1403 tok_expect(';');
1404 return;
1406 if (!tok_jmp(TOK_IF)) {
1407 int l_fail = LABEL();
1408 int l_end = LABEL();
1409 tok_expect('(');
1410 readestmt();
1411 tok_expect(')');
1412 ts_pop_de(NULL);
1413 o_jz(l_fail);
1414 readstmt();
1415 if (!tok_jmp(TOK_ELSE)) {
1416 o_jmp(l_end);
1417 o_label(l_fail);
1418 readstmt();
1419 o_label(l_end);
1420 } else {
1421 o_label(l_fail);
1423 return;
1425 if (!tok_jmp(TOK_WHILE)) {
1426 int o_break = l_break;
1427 int o_cont = l_cont;
1428 l_break = LABEL();
1429 l_cont = LABEL();
1430 o_label(l_cont);
1431 tok_expect('(');
1432 readestmt();
1433 tok_expect(')');
1434 ts_pop_de(NULL);
1435 o_jz(l_break);
1436 readstmt();
1437 o_jmp(l_cont);
1438 o_label(l_break);
1439 l_break = o_break;
1440 l_cont = o_cont;
1441 return;
1443 if (!tok_jmp(TOK_DO)) {
1444 int o_break = l_break;
1445 int o_cont = l_cont;
1446 int l_beg = LABEL();
1447 l_break = LABEL();
1448 l_cont = LABEL();
1449 o_label(l_beg);
1450 readstmt();
1451 tok_expect(TOK_WHILE);
1452 tok_expect('(');
1453 o_label(l_cont);
1454 readexpr();
1455 ts_pop_de(NULL);
1456 o_jnz(l_beg);
1457 tok_expect(')');
1458 o_label(l_break);
1459 tok_expect(';');
1460 l_break = o_break;
1461 l_cont = o_cont;
1462 return;
1464 if (!tok_jmp(TOK_FOR)) {
1465 int o_break = l_break;
1466 int o_cont = l_cont;
1467 int l_check = LABEL(); /* for condition label */
1468 int l_body = LABEL(); /* for block label */
1469 l_cont = LABEL();
1470 l_break = LABEL();
1471 tok_expect('(');
1472 if (tok_see() != ';')
1473 readestmt();
1474 tok_expect(';');
1475 o_label(l_check);
1476 if (tok_see() != ';') {
1477 readestmt();
1478 ts_pop_de(NULL);
1479 o_jz(l_break);
1481 tok_expect(';');
1482 o_jmp(l_body);
1483 o_label(l_cont);
1484 if (tok_see() != ')')
1485 readestmt();
1486 tok_expect(')');
1487 o_jmp(l_check);
1488 o_label(l_body);
1489 readstmt();
1490 o_jmp(l_cont);
1491 o_label(l_break);
1492 l_break = o_break;
1493 l_cont = o_cont;
1494 return;
1496 if (!tok_jmp(TOK_SWITCH)) {
1497 readswitch();
1498 return;
1500 if (!tok_jmp(TOK_RETURN)) {
1501 int ret = tok_see() != ';';
1502 if (ret) {
1503 readexpr();
1504 ts_pop_de(NULL);
1506 tok_expect(';');
1507 o_ret(ret);
1508 return;
1510 if (!tok_jmp(TOK_BREAK)) {
1511 tok_expect(';');
1512 o_jmp(l_break);
1513 return;
1515 if (!tok_jmp(TOK_CONTINUE)) {
1516 tok_expect(';');
1517 o_jmp(l_cont);
1518 return;
1520 if (!tok_jmp(TOK_GOTO)) {
1521 tok_expect(TOK_NAME);
1522 o_jmp(label_id(tok_id()));
1523 tok_expect(';');
1524 return;
1526 readestmt();
1527 /* labels */
1528 if (!tok_jmp(':')) {
1529 o_label(label_id(tok_id()));
1530 return;
1532 tok_expect(';');
1535 static void readfunc(struct name *name, int flags)
1537 struct funcinfo *fi = &funcs[name->type.id];
1538 long beg = tok_addr();
1539 int i;
1540 strcpy(func_name, fi->name);
1541 o_func_beg(func_name, fi->nargs, F_GLOBAL(flags), fi->varg);
1542 for (i = 0; i < fi->nargs; i++) {
1543 struct name arg = {"", "", fi->args[i], o_arg2loc(i)};
1544 strcpy(arg.name, fi->argnames[i]);
1545 local_add(&arg);
1547 /* first pass: collecting statistics */
1548 label = 0;
1549 nlabels = 0;
1550 o_pass1();
1551 readstmt();
1552 tok_jump(beg);
1553 /* second pass: generating code */
1554 label = 0;
1555 nlabels = 0;
1556 o_pass2();
1557 readstmt();
1558 o_func_end();
1559 func_name[0] = '\0';
1560 nlocals = 0;
1563 static void readdecl(void)
1565 if (!tok_jmp(TOK_TYPEDEF)) {
1566 readdefs(typedefdef, NULL);
1567 tok_expect(';');
1568 return;
1570 readdefs_int(globaldef, NULL);
1571 tok_jmp(';');
1574 static void parse(void)
1576 while (tok_see() != TOK_EOF)
1577 readdecl();
1580 static void compat_macros(void)
1582 cpp_define("__STDC__", "");
1583 cpp_define("__linux__", "");
1584 cpp_define(I_ARCH, "");
1586 /* ignored keywords */
1587 cpp_define("const", "");
1588 cpp_define("register", "");
1589 cpp_define("volatile", "");
1590 cpp_define("inline", "");
1591 cpp_define("restrict", "");
1592 cpp_define("__inline__", "");
1593 cpp_define("__restrict__", "");
1594 cpp_define("__attribute__(x)", "");
1595 cpp_define("__builtin_va_list__", "long");
1598 int main(int argc, char *argv[])
1600 char obj[128] = "";
1601 int ofd;
1602 int i = 1;
1603 compat_macros();
1604 while (i < argc && argv[i][0] == '-') {
1605 if (argv[i][1] == 'I')
1606 cpp_addpath(argv[i][2] ? argv[i] + 2 : argv[++i]);
1607 if (argv[i][1] == 'D') {
1608 char *name = argv[i] + 2;
1609 char *def = "";
1610 char *eq = strchr(name, '=');
1611 if (eq) {
1612 *eq = '\0';
1613 def = eq + 1;
1615 cpp_define(name, def);
1617 if (argv[i][1] == 'o')
1618 strcpy(obj, argv[i][2] ? argv[i] + 2 : argv[++i]);
1619 i++;
1621 if (i == argc)
1622 die("neatcc: no file given\n");
1623 if (cpp_init(argv[i]))
1624 die("neatcc: cannot open <%s>\n", argv[i]);
1625 parse();
1626 if (!*obj) {
1627 strcpy(obj, argv[i]);
1628 obj[strlen(obj) - 1] = 'o';
1630 ofd = open(obj, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1631 o_write(ofd);
1632 close(ofd);
1633 return 0;
1637 /* parsing function and variable declarations */
1639 /* read the base type of a variable */
1640 static int basetype(struct type *type, unsigned *flags)
1642 int sign = 1;
1643 int size = 4;
1644 int done = 0;
1645 int i = 0;
1646 int isunion;
1647 char name[NAMELEN] = "";
1648 *flags = 0;
1649 type->flags = 0;
1650 type->ptr = 0;
1651 type->addr = 0;
1652 while (!done) {
1653 switch (tok_see()) {
1654 case TOK_STATIC:
1655 *flags |= F_STATIC;
1656 break;
1657 case TOK_EXTERN:
1658 *flags |= F_EXTERN;
1659 break;
1660 case TOK_VOID:
1661 sign = 0;
1662 size = 0;
1663 done = 1;
1664 break;
1665 case TOK_INT:
1666 done = 1;
1667 break;
1668 case TOK_CHAR:
1669 size = 1;
1670 done = 1;
1671 break;
1672 case TOK_SHORT:
1673 size = 2;
1674 break;
1675 case TOK_LONG:
1676 size = LONGSZ;
1677 break;
1678 case TOK_SIGNED:
1679 break;
1680 case TOK_UNSIGNED:
1681 sign = 0;
1682 break;
1683 case TOK_UNION:
1684 case TOK_STRUCT:
1685 isunion = tok_get() == TOK_UNION;
1686 if (!tok_jmp(TOK_NAME))
1687 strcpy(name, tok_id());
1688 if (tok_see() == '{')
1689 type->id = struct_create(name, isunion);
1690 else
1691 type->id = struct_find(name, isunion);
1692 type->flags |= T_STRUCT;
1693 type->bt = LONGSZ;
1694 return 0;
1695 case TOK_ENUM:
1696 tok_get();
1697 tok_jmp(TOK_NAME);
1698 if (tok_see() == '{')
1699 enum_create();
1700 type->bt = 4 | BT_SIGNED;
1701 return 0;
1702 default:
1703 if (tok_see() == TOK_NAME) {
1704 int id = typedef_find(tok_id());
1705 if (id != -1) {
1706 tok_get();
1707 memcpy(type, &typedefs[id].type,
1708 sizeof(*type));
1709 return 0;
1712 if (!i)
1713 return 1;
1714 done = 1;
1715 continue;
1717 i++;
1718 tok_get();
1720 type->bt = size | (sign ? BT_SIGNED : 0);
1721 return 0;
1724 static void readptrs(struct type *type)
1726 while (!tok_jmp('*')) {
1727 type->ptr++;
1728 if (!type->bt)
1729 type->bt = 1;
1733 /* read function arguments */
1734 static int readargs(struct type *args, char argnames[][NAMELEN], int *varg)
1736 int nargs = 0;
1737 tok_expect('(');
1738 *varg = 0;
1739 while (tok_see() != ')') {
1740 if (!tok_jmp(TOK3("..."))) {
1741 *varg = 1;
1742 break;
1744 if (readname(&args[nargs], argnames[nargs], NULL)) {
1745 /* argument has no type, assume int */
1746 tok_expect(TOK_NAME);
1747 memset(&args[nargs], 0, sizeof(struct type));
1748 args[nargs].bt = 4 | BT_SIGNED;
1749 strcpy(argnames[nargs], tok_id());
1751 /* argument arrays are pointers */
1752 array2ptr(&args[nargs]);
1753 nargs++;
1754 if (tok_jmp(','))
1755 break;
1757 tok_expect(')');
1758 /* void argument */
1759 if (nargs == 1 && !TYPE_BT(&args[0]))
1760 return 0;
1761 return nargs;
1764 /* read K&R function arguments */
1765 static void krdef(void *data, struct name *name, unsigned flags)
1767 struct funcinfo *fi = data;
1768 int i;
1769 for (i = 0; i < fi->nargs; i++)
1770 if (!strcmp(fi->argnames[i], name->name))
1771 memcpy(&fi->args[i], &name->type, sizeof(name->type));
1775 * readarrays() parses array specifiers when reading a definition in
1776 * readname(). The "type" parameter contains the type contained in the
1777 * inner array; for instance, type in "int *a[10][20]" would be an int
1778 * pointer. When returning, the "type" parameter is changed to point
1779 * to the final array. The function returns a pointer to the type in
1780 * the inner array; this is useful when the type is not complete yet,
1781 * like when creating an array of function pointers as in
1782 * "int (*f[10])(int)". If there is no array brackets, NULL is returned.
1784 static struct type *readarrays(struct type *type)
1786 long arsz[16];
1787 struct type *inner = NULL;
1788 int nar = 0;
1789 int i;
1790 while (!tok_jmp('[')) {
1791 long n = 0;
1792 if (tok_jmp(']')) {
1793 readexpr();
1794 ts_pop_de(NULL);
1795 if (o_popnum(&n))
1796 err("const expr expected\n");
1797 tok_expect(']');
1799 arsz[nar++] = n;
1801 for (i = nar - 1; i >= 0; i--) {
1802 type->id = array_add(type, arsz[i]);
1803 if (!inner)
1804 inner = &arrays[type->id].type;
1805 type->flags = T_ARRAY;
1806 type->bt = LONGSZ;
1807 type->ptr = 0;
1809 return inner;
1813 * readname() reads a variable definition; the name is copied into
1814 * "name" and the type is copied into "main" argument. The "base"
1815 * argument, if not NULL, indicates the base type of the variable.
1816 * For instance, the base type of "a" and "b" in "int *a, b[10]" is
1817 * "int". If NULL, basetype() is called directly to read the base
1818 * type of the variable. readname() returns zero, only if the
1819 * variable can be read.
1821 static int readname(struct type *main, char *name, struct type *base)
1823 struct type tpool[3];
1824 int npool = 0;
1825 struct type *type = &tpool[npool++];
1826 struct type *ptype = NULL; /* type inside parenthesis */
1827 struct type *btype = NULL; /* type before parenthesis */
1828 struct type *inner;
1829 unsigned flags;
1830 memset(tpool, 0, sizeof(tpool));
1831 if (name)
1832 *name = '\0';
1833 if (!base) {
1834 if (basetype(type, &flags))
1835 return 1;
1836 } else {
1837 memcpy(type, base, sizeof(*base));
1839 readptrs(type);
1840 if (!tok_jmp('(')) {
1841 btype = type;
1842 type = &tpool[npool++];
1843 ptype = type;
1844 readptrs(type);
1846 if (!tok_jmp(TOK_NAME) && name)
1847 strcpy(name, tok_id());
1848 inner = readarrays(type);
1849 if (ptype && inner)
1850 ptype = inner;
1851 if (ptype)
1852 tok_expect(')');
1853 if (tok_see() == '(') {
1854 struct type args[NARGS];
1855 char argnames[NARGS][NAMELEN];
1856 int varg = 0;
1857 int nargs = readargs(args, argnames, &varg);
1858 if (!ptype) {
1859 btype = type;
1860 type = &tpool[npool++];
1861 ptype = type;
1863 ptype->flags = T_FUNC;
1864 ptype->bt = LONGSZ;
1865 ptype->id = func_create(btype, name, argnames, args, nargs, varg);
1866 if (tok_see() != ';')
1867 while (tok_see() != '{' && !readdefs(krdef, &funcs[ptype->id]))
1868 tok_expect(';');
1869 } else {
1870 if (ptype && readarrays(type))
1871 array2ptr(type);
1873 memcpy(main, type, sizeof(*type));
1874 return 0;
1877 static int readtype(struct type *type)
1879 return readname(type, NULL, NULL);
1883 * readdef() reads a variable definitions statement. The definition
1884 * statement can appear in anywhere: global variables, function
1885 * local variables, struct fields, and typedefs. For each defined
1886 * variable, def() callback is called with the appropriate name
1887 * struct and flags; the callback should finish parsing the definition
1888 * by possibly reading the initializer expression and saving the name
1889 * struct.
1891 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
1892 void *data)
1894 struct type base;
1895 unsigned base_flags;
1896 if (basetype(&base, &base_flags))
1897 return 1;
1898 if (tok_see() == ';' || tok_see() == '{')
1899 return 0;
1900 do {
1901 struct name name = {{""}};
1902 if (readname(&name.type, name.name, &base))
1903 break;
1904 def(data, &name, base_flags);
1905 } while (!tok_jmp(','));
1906 return 0;
1909 /* just like readdefs, but default to int type; for handling K&R functions */
1910 static int readdefs_int(void (*def)(void *data, struct name *name, unsigned flags),
1911 void *data)
1913 struct type base;
1914 unsigned flags = 0;
1915 if (basetype(&base, &flags)) {
1916 if (tok_see() != TOK_NAME)
1917 return 1;
1918 memset(&base, 0, sizeof(base));
1919 base.bt = 4 | BT_SIGNED;
1921 if (tok_see() != ';') {
1922 do {
1923 struct name name = {{""}};
1924 if (readname(&name.type, name.name, &base))
1925 break;
1926 def(data, &name, flags);
1927 } while (!tok_jmp(','));
1929 return 0;
1933 /* parsing initializer expressions */
1935 static void jumpbrace(void)
1937 int depth = 0;
1938 while (tok_see() != '}' || depth--)
1939 if (tok_get() == '{')
1940 depth++;
1941 tok_expect('}');
1944 /* compute the size of the initializer expression */
1945 static int initsize(void)
1947 long addr = tok_addr();
1948 int n = 0;
1949 if (tok_jmp('='))
1950 return 0;
1951 if (!tok_jmp(TOK_STR)) {
1952 tok_str(NULL, &n);
1953 tok_jump(addr);
1954 return n;
1956 tok_expect('{');
1957 while (tok_jmp('}')) {
1958 long idx = n;
1959 if (!tok_jmp('[')) {
1960 readexpr();
1961 ts_pop_de(NULL);
1962 o_popnum(&idx);
1963 tok_expect(']');
1964 tok_expect('=');
1966 if (n < idx + 1)
1967 n = idx + 1;
1968 while (tok_see() != '}' && tok_see() != ',')
1969 if (tok_get() == '{')
1970 jumpbrace();
1971 tok_jmp(',');
1973 tok_jump(addr);
1974 return n;
1977 static struct type *innertype(struct type *t)
1979 if (t->flags & T_ARRAY && !t->ptr)
1980 return innertype(&arrays[t->id].type);
1981 return t;
1984 /* read the initializer expression and initialize basic types using set() cb */
1985 static void initexpr(struct type *t, int off, void *obj,
1986 void (*set)(void *obj, int off, struct type *t))
1988 if (tok_jmp('{')) {
1989 set(obj, off, t);
1990 return;
1992 if (!t->ptr && t->flags & T_STRUCT) {
1993 struct structinfo *si = &structs[t->id];
1994 int i;
1995 for (i = 0; i < si->nfields && tok_see() != '}'; i++) {
1996 struct name *field = &si->fields[i];
1997 if (!tok_jmp('.')) {
1998 tok_expect(TOK_NAME);
1999 field = struct_field(t->id, tok_id());
2000 tok_expect('=');
2002 initexpr(&field->type, off + field->addr, obj, set);
2003 if (tok_jmp(','))
2004 break;
2006 } else if (t->flags & T_ARRAY) {
2007 struct type *t_de = &arrays[t->id].type;
2008 int i;
2009 /* handling extra braces as in: char s[] = {"sth"} */
2010 if (TYPE_SZ(t_de) == 1 && tok_see() == TOK_STR) {
2011 set(obj, off, t);
2012 tok_expect('}');
2013 return;
2015 for (i = 0; tok_see() != '}'; i++) {
2016 long idx = i;
2017 struct type *it = t_de;
2018 if (!tok_jmp('[')) {
2019 readexpr();
2020 ts_pop_de(NULL);
2021 o_popnum(&idx);
2022 tok_expect(']');
2023 tok_expect('=');
2025 if (tok_see() != '{' && (tok_see() != TOK_STR ||
2026 !(it->flags & T_ARRAY)))
2027 it = innertype(t_de);
2028 initexpr(it, off + type_totsz(it) * idx, obj, set);
2029 if (tok_jmp(','))
2030 break;
2033 tok_expect('}');