ncc: switch to the modified bsd license
[neatcc.git] / ncc.c
blob628c42295bf7e7f32acc185af72ae413b247c0f8
1 /*
2 * neatcc - a small and simple C compiler
4 * Copyright (C) 2010-2012 Ali Gholami Rudi
6 * This program is released under the modified BSD license.
7 */
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <stdarg.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <stdio.h>
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 #include "gen.h"
17 #include "tok.h"
18 #include "out.h"
20 static int nogen; /* don't generate code */
21 /* nogen macros */
22 #define o_bop(op) {if (!nogen) o_bop(op);}
23 #define o_uop(op) {if (!nogen) o_uop(op);}
24 #define o_cast(bt) {if (!nogen) o_cast(bt);}
25 #define o_memcpy() {if (!nogen) o_memcpy();}
26 #define o_memset() {if (!nogen) o_memset();}
27 #define o_call(argc, ret) {if (!nogen) o_call(argc, ret);}
28 #define o_ret(ret) {if (!nogen) o_ret(ret);}
29 #define o_assign(bt) {if (!nogen) o_assign(bt);}
30 #define o_deref(bt) {if (!nogen) o_deref(bt);}
31 #define o_load() {if (!nogen) o_load();}
32 #define o_popnum(c) (nogen ? 0 : o_popnum(c))
33 #define o_num(n) {if (!nogen) o_num(n);}
34 #define o_local(addr) {if (!nogen) o_local(addr);}
35 #define o_sym(sym) {if (!nogen) o_sym(sym);}
36 #define o_tmpdrop(n) {if (!nogen) o_tmpdrop(n);}
37 #define o_tmpswap() {if (!nogen) o_tmpswap();}
38 #define o_tmpcopy() {if (!nogen) o_tmpcopy();}
39 #define o_label(id) {if (!nogen) o_label(id);}
40 #define o_jz(id) {if (!nogen) o_jz(id);}
41 #define o_jnz(id) {if (!nogen) o_jnz(id);}
42 #define o_jmp(id) {if (!nogen) o_jmp(id);}
43 #define o_fork() {if (!nogen) o_fork();}
44 #define o_forkpush() {if (!nogen) o_forkpush();}
45 #define o_forkjoin() {if (!nogen) o_forkjoin();}
47 #define MAXLOCALS (1 << 10)
48 #define MAXGLOBALS (1 << 10)
49 #define MAXARGS (1 << 5)
51 #define ALIGN(x, a) (((x) + (a) - 1) & ~((a) - 1))
52 #define MIN(a, b) ((a) < (b) ? (a) : (b))
54 #define TYPE_BT(t) ((t)->ptr ? LONGSZ : (t)->bt)
55 #define TYPE_SZ(t) ((t)->ptr ? LONGSZ : (t)->bt & BT_SZMASK)
56 #define TYPE_VOID(t) (!(t)->bt && !(t)->flags && !(t)->ptr)
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 *fmt, ...)
108 va_list ap;
109 char msg[512];
110 va_start(ap, fmt);
111 vsprintf(msg, fmt, ap);
112 va_end(ap);
113 die("%s: %s", cpp_loc(tok_addr()), msg);
116 struct name {
117 char name[NAMELEN];
118 char elfname[NAMELEN]; /* local elf name for static variables in function */
119 struct type type;
120 long addr; /* local stack offset, global data addr, struct offset */
123 static struct name locals[MAXLOCALS];
124 static int nlocals;
125 static struct name globals[MAXGLOBALS];
126 static int nglobals;
128 static void local_add(struct name *name)
130 if (nlocals >= MAXLOCALS)
131 err("nomem: MAXLOCALS reached!\n");
132 memcpy(&locals[nlocals++], name, sizeof(*name));
135 static int local_find(char *name)
137 int i;
138 for (i = nlocals - 1; i >= 0; --i)
139 if (!strcmp(locals[i].name, name))
140 return i;
141 return -1;
144 static int global_find(char *name)
146 int i;
147 for (i = nglobals - 1; i >= 0; i--)
148 if (!strcmp(name, globals[i].name))
149 return i;
150 return -1;
153 static void global_add(struct name *name)
155 if (nglobals >= MAXGLOBALS)
156 err("nomem: MAXGLOBALS reached!\n");
157 memcpy(&globals[nglobals++], name, sizeof(*name));
160 #define LABEL() (++label)
162 static int label; /* last used label id */
163 static int l_break; /* current break label */
164 static int l_cont; /* current continue label */
166 #define MAXENUMS (1 << 10)
168 static struct enumval {
169 char name[NAMELEN];
170 int n;
171 } enums[MAXENUMS];
172 static int nenums;
174 static void enum_add(char *name, int val)
176 struct enumval *ev = &enums[nenums++];
177 if (nenums >= MAXENUMS)
178 err("nomem: MAXENUMS reached!\n");
179 strcpy(ev->name, name);
180 ev->n = val;
183 static int enum_find(int *val, char *name)
185 int i;
186 for (i = nenums - 1; i >= 0; --i)
187 if (!strcmp(name, enums[i].name)) {
188 *val = enums[i].n;
189 return 0;
191 return 1;
194 #define MAXTYPEDEFS (1 << 10)
196 static struct typdefinfo {
197 char name[NAMELEN];
198 struct type type;
199 } typedefs[MAXTYPEDEFS];
200 static int ntypedefs;
202 static void typedef_add(char *name, struct type *type)
204 struct typdefinfo *ti = &typedefs[ntypedefs++];
205 if (ntypedefs >= MAXTYPEDEFS)
206 err("nomem: MAXTYPEDEFS reached!\n");
207 strcpy(ti->name, name);
208 memcpy(&ti->type, type, sizeof(*type));
211 static int typedef_find(char *name)
213 int i;
214 for (i = ntypedefs - 1; i >= 0; --i)
215 if (!strcmp(name, typedefs[i].name))
216 return i;
217 return -1;
220 #define MAXARRAYS (1 << 10)
222 static struct array {
223 struct type type;
224 int n;
225 } arrays[MAXARRAYS];
226 static int narrays;
228 static int array_add(struct type *type, int n)
230 struct array *a = &arrays[narrays++];
231 if (narrays >= MAXARRAYS)
232 err("nomem: MAXARRAYS reached!\n");
233 memcpy(&a->type, type, sizeof(*type));
234 a->n = n;
235 return a - arrays;
238 static void array2ptr(struct type *t)
240 if (t->flags & T_ARRAY && !t->ptr) {
241 memcpy(t, &arrays[t->id].type, sizeof(*t));
242 t->ptr++;
246 #define MAXSTRUCTS (1 << 10)
247 #define MAXFIELDS (1 << 7)
249 static struct structinfo {
250 char name[NAMELEN];
251 struct name fields[MAXFIELDS];
252 int nfields;
253 int isunion;
254 int size;
255 } structs[MAXSTRUCTS];
256 static int nstructs;
258 static int struct_find(char *name, int isunion)
260 int i;
261 for (i = nstructs - 1; i >= 0; --i)
262 if (*structs[i].name && !strcmp(name, structs[i].name) &&
263 structs[i].isunion == isunion)
264 return i;
265 i = nstructs++;
266 if (nstructs >= MAXSTRUCTS)
267 err("nomem: MAXTYPES reached!\n");
268 memset(&structs[i], 0, sizeof(structs[i]));
269 strcpy(structs[i].name, name);
270 structs[i].isunion = isunion;
271 return i;
274 static struct name *struct_field(int id, char *name)
276 struct structinfo *si = &structs[id];
277 int i;
278 for (i = 0; i < si->nfields; i++)
279 if (!strcmp(name, si->fields[i].name))
280 return &si->fields[i];
281 err("field not found\n");
282 return NULL;
285 /* return t's size */
286 static int type_totsz(struct type *t)
288 if (t->ptr)
289 return LONGSZ;
290 if (t->flags & T_ARRAY)
291 return arrays[t->id].n * type_totsz(&arrays[t->id].type);
292 return t->flags & T_STRUCT ? structs[t->id].size : BT_SZ(t->bt);
295 /* return t's dereferenced size */
296 static unsigned type_szde(struct type *t)
298 struct type de = *t;
299 array2ptr(&de);
300 de.ptr--;
301 return type_totsz(&de);
304 /* dereference stack top if t->addr (ie. address is pushed to gen.c) */
305 static void ts_de(int deref)
307 struct type *t = &ts[nts - 1];
308 array2ptr(t);
309 if (deref && t->addr && (t->ptr || !(t->flags & T_FUNC)))
310 o_deref(TYPE_BT(t));
311 t->addr = 0;
314 /* pop stack pop to *t and dereference if t->addr */
315 static void ts_pop_de(struct type *t)
317 ts_de(1);
318 ts_pop(t);
321 /* pop the top 2 stack values and dereference them if t->addr */
322 static void ts_pop_de2(struct type *t1, struct type *t2)
324 ts_pop_de(t1);
325 o_tmpswap();
326 ts_pop_de(t2);
327 o_tmpswap();
330 static int tok_jmp(int tok)
332 if (tok_see() != tok)
333 return 1;
334 tok_get();
335 return 0;
338 static void tok_expect(int tok)
340 if (tok_get() != tok)
341 err("syntax error\n");
344 static unsigned bt_op(unsigned bt1, unsigned bt2)
346 unsigned s1 = BT_SZ(bt1);
347 unsigned s2 = BT_SZ(bt2);
348 return ((bt1 | bt2) & BT_SIGNED) | (s1 > s2 ? s1 : s2);
351 static void ts_binop(int op)
353 struct type t1, t2;
354 int bt;
355 ts_pop_de2(&t1, &t2);
356 if (op == O_DIV || op == O_MOD)
357 bt = TYPE_BT(&t2);
358 else
359 bt = bt_op(TYPE_BT(&t1), TYPE_BT(&t2));
360 o_bop(op | (bt & BT_SIGNED ? O_SIGNED : 0));
361 ts_push_bt(bt);
364 static void ts_addop(int op)
366 struct type t1, t2;
367 ts_pop_de2(&t1, &t2);
368 if (!t1.ptr && !t2.ptr) {
369 o_bop(op);
370 ts_push_bt(bt_op(TYPE_BT(&t1), TYPE_BT(&t2)));
371 return;
373 if (t1.ptr && !t2.ptr)
374 o_tmpswap();
375 if (!t1.ptr && t2.ptr)
376 if (type_szde(&t2) > 1) {
377 o_num(type_szde(&t2));
378 o_bop(O_MUL);
380 if (t1.ptr && !t2.ptr)
381 o_tmpswap();
382 o_bop(op);
383 if (t1.ptr && t2.ptr) {
384 int sz = type_szde(&t1);
385 if (sz > 1) {
386 o_num(sz);
387 o_bop(O_DIV);
389 ts_push_bt(4 | BT_SIGNED);
390 } else {
391 ts_push(t1.ptr ? &t1 : &t2);
395 /* function prototypes for parsing function and variable declarations */
396 static int readname(struct type *main, char *name, struct type *base);
397 static int readtype(struct type *type);
398 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
399 void *data);
400 static int readdefs_int(void (*def)(void *data, struct name *name, unsigned flags),
401 void *data);
403 /* function prototypes for parsing initializer expressions */
404 static int initsize(void);
405 static void initexpr(struct type *t, int off, void *obj,
406 void (*set)(void *obj, int off, struct type *t));
408 static int type_alignment(struct type *t)
410 if (t->flags & T_ARRAY && !t->ptr)
411 return type_alignment(&arrays[t->id].type);
412 if (t->flags & T_STRUCT && !t->ptr)
413 return type_alignment(&structs[t->id].fields[0].type);
414 return MIN(LONGSZ, type_totsz(t));
417 static void structdef(void *data, struct name *name, unsigned flags)
419 struct structinfo *si = data;
420 if (si->isunion) {
421 name->addr = 0;
422 if (si->size < type_totsz(&name->type))
423 si->size = type_totsz(&name->type);
424 } else {
425 struct type *t = &name->type;
426 int alignment = type_alignment(t);
427 if (t->flags & T_ARRAY && !t->ptr)
428 alignment = MIN(LONGSZ, type_totsz(&arrays[t->id].type));
429 si->size = ALIGN(si->size, alignment);
430 name->addr = si->size;
431 si->size += type_totsz(&name->type);
433 memcpy(&si->fields[si->nfields++], name, sizeof(*name));
436 static int struct_create(char *name, int isunion)
438 int id = struct_find(name, isunion);
439 struct structinfo *si = &structs[id];
440 tok_expect('{');
441 while (tok_jmp('}')) {
442 readdefs(structdef, si);
443 tok_expect(';');
445 return id;
448 static void readexpr(void);
450 static void enum_create(void)
452 long n = 0;
453 tok_expect('{');
454 while (tok_jmp('}')) {
455 char name[NAMELEN];
456 tok_expect(TOK_NAME);
457 strcpy(name, tok_id());
458 if (!tok_jmp('=')) {
459 readexpr();
460 ts_pop_de(NULL);
461 if (o_popnum(&n))
462 err("const expr expected!\n");
464 enum_add(name, n++);
465 tok_jmp(',');
469 /* used to differenciate labels from case and cond exprs */
470 static int ncexpr;
471 static int caseexpr;
473 static void readpre(void);
475 static char *tmp_str(char *buf, int len)
477 static char name[NAMELEN];
478 static int id;
479 void *dat;
480 sprintf(name, "__neatcc.s%d", id++);
481 dat = o_mkdat(name, len, 0);
482 memcpy(dat, buf, len);
483 return name;
486 static void readprimary(void)
488 if (!tok_jmp(TOK_NUM)) {
489 long n;
490 int bt = tok_num(&n);
491 ts_push_bt(bt);
492 o_num(n);
493 return;
495 if (!tok_jmp(TOK_STR)) {
496 struct type t = {}; /* char type inside the arrays */
497 struct type a = {}; /* the char array type */
498 char buf[BUFSIZE];
499 int len = tok_str(buf);
500 t.bt = 1 | BT_SIGNED;
501 a.id = array_add(&t, len);
502 a.flags = T_ARRAY;
503 ts_push(&a);
504 o_sym(tmp_str(buf, len));
505 return;
507 if (!tok_jmp(TOK_NAME)) {
508 struct name unkn = {""};
509 char *name = unkn.name;
510 int n;
511 strcpy(name, tok_id());
512 /* don't search for labels here */
513 if (!ncexpr && !caseexpr && tok_see() == ':')
514 return;
515 if ((n = local_find(name)) != -1) {
516 struct name *l = &locals[n];
517 o_local(l->addr);
518 ts_push_addr(&l->type);
519 return;
521 if ((n = global_find(name)) != -1) {
522 struct name *g = &globals[n];
523 o_sym(*g->elfname ? g->elfname : g->name);
524 ts_push_addr(&g->type);
525 return;
527 if (!enum_find(&n, name)) {
528 ts_push_bt(4 | BT_SIGNED);
529 o_num(n);
530 return;
532 if (tok_see() != '(')
533 err("unknown symbol <%s>\n", name);
534 global_add(&unkn);
535 ts_push_bt(LONGSZ);
536 o_sym(unkn.name);
537 return;
539 if (!tok_jmp('(')) {
540 struct type t;
541 if (!readtype(&t)) {
542 struct type o;
543 tok_expect(')');
544 readpre();
545 ts_pop_de(&o);
546 ts_push(&t);
547 if (!t.ptr || !o.ptr)
548 o_cast(TYPE_BT(&t));
549 } else {
550 readexpr();
551 while (tok_jmp(')')) {
552 tok_expect(',');
553 ts_pop(NULL);
554 o_tmpdrop(1);
555 readexpr();
558 return;
562 static void arrayderef(void)
564 struct type t;
565 int sz;
566 ts_pop_de(NULL);
567 ts_pop(&t);
568 if (!(t.flags & T_ARRAY && !t.ptr) && t.addr) {
569 o_tmpswap();
570 o_deref(TYPE_BT(&t));
571 o_tmpswap();
573 array2ptr(&t);
574 t.ptr--;
575 sz = type_totsz(&t);
576 t.addr = 1;
577 if (sz > 1) {
578 o_num(sz);
579 o_bop(O_MUL);
581 o_bop(O_ADD);
582 ts_push(&t);
585 static void inc_post(int op)
587 struct type t = ts[nts - 1];
588 /* pushing the value before inc */
589 o_tmpcopy();
590 ts_de(1);
591 o_load();
592 o_tmpswap();
594 /* increment by 1 or pointer size */
595 o_tmpcopy();
596 ts_push(&t);
597 ts_pop_de(&t);
598 o_num(t.ptr > 0 ? type_szde(&t) : 1);
599 o_bop(op);
601 /* assign back */
602 o_assign(TYPE_BT(&t));
603 o_tmpdrop(1);
606 static void readfield(void)
608 struct name *field;
609 struct type t;
610 tok_expect(TOK_NAME);
611 ts_pop(&t);
612 array2ptr(&t);
613 field = struct_field(t.id, tok_id());
614 if (field->addr) {
615 o_num(field->addr);
616 o_bop(O_ADD);
618 ts_push_addr(&field->type);
621 #define MAXFUNCS (1 << 10)
623 static struct funcinfo {
624 struct type args[MAXARGS];
625 struct type ret;
626 int nargs;
627 int varg;
628 /* function and argument names; useful only when defining */
629 char argnames[MAXARGS][NAMELEN];
630 char name[NAMELEN];
631 } funcs[MAXFUNCS];
632 static int nfuncs;
634 static int func_create(struct type *ret, char *name, char argnames[][NAMELEN],
635 struct type *args, int nargs, int varg)
637 struct funcinfo *fi = &funcs[nfuncs++];
638 int i;
639 if (nfuncs >= MAXFUNCS)
640 err("nomem: MAXFUNCS reached!\n");
641 memcpy(&fi->ret, ret, sizeof(*ret));
642 for (i = 0; i < nargs; i++)
643 memcpy(&fi->args[i], &args[i], sizeof(*ret));
644 fi->nargs = nargs;
645 fi->varg = varg;
646 strcpy(fi->name, name ? name : "");
647 for (i = 0; i < nargs; i++)
648 strcpy(fi->argnames[i], argnames[i]);
649 return fi - funcs;
652 static void readcall(void)
654 struct type t;
655 struct funcinfo *fi;
656 int argc = 0;
657 ts_pop(&t);
658 if (t.flags & T_FUNC && t.ptr > 0)
659 o_deref(LONGSZ);
660 fi = t.flags & T_FUNC ? &funcs[t.id] : NULL;
661 if (tok_see() != ')') {
662 do {
663 readexpr();
664 ts_pop_de(NULL);
665 argc++;
666 } while (!tok_jmp(','));
668 tok_expect(')');
669 o_call(argc, fi ? TYPE_BT(&fi->ret) : 4 | BT_SIGNED);
670 if (fi) {
671 if (TYPE_BT(&fi->ret))
672 o_cast(TYPE_BT(&fi->ret));
673 ts_push(&fi->ret);
674 } else {
675 ts_push_bt(4 | BT_SIGNED);
679 static void readpost(void)
681 readprimary();
682 while (1) {
683 if (!tok_jmp('[')) {
684 readexpr();
685 tok_expect(']');
686 arrayderef();
687 continue;
689 if (!tok_jmp('(')) {
690 readcall();
691 continue;
693 if (!tok_jmp(TOK2("++"))) {
694 inc_post(O_ADD);
695 continue;
697 if (!tok_jmp(TOK2("--"))) {
698 inc_post(O_SUB);
699 continue;
701 if (!tok_jmp('.')) {
702 readfield();
703 continue;
705 if (!tok_jmp(TOK2("->"))) {
706 ts_de(1);
707 readfield();
708 continue;
710 break;
714 static void inc_pre(int op)
716 struct type t;
717 readpre();
718 /* copy the destination */
719 o_tmpcopy();
720 ts_push(&ts[nts - 1]);
721 /* increment by 1 or pointer size */
722 ts_pop_de(&t);
723 o_num(t.ptr > 0 ? type_szde(&t) : 1);
724 o_bop(op);
725 /* assign the result */
726 o_assign(TYPE_BT(&t));
727 ts_de(0);
730 static void readpre(void)
732 if (!tok_jmp('&')) {
733 struct type type;
734 readpre();
735 ts_pop(&type);
736 if (!type.addr)
737 err("cannot use the address\n");
738 type.ptr++;
739 type.addr = 0;
740 ts_push(&type);
741 return;
743 if (!tok_jmp('*')) {
744 struct type t;
745 readpre();
746 ts_pop(&t);
747 array2ptr(&t);
748 if (!t.ptr)
749 err("dereferencing non-pointer\n");
750 if (t.addr)
751 o_deref(TYPE_BT(&t));
752 t.ptr--;
753 t.addr = 1;
754 ts_push(&t);
755 return;
757 if (!tok_jmp('!')) {
758 readpre();
759 ts_pop_de(NULL);
760 o_uop(O_LNOT);
761 ts_push_bt(4 | BT_SIGNED);
762 return;
764 if (!tok_jmp('-')) {
765 readpre();
766 ts_de(1);
767 o_uop(O_NEG);
768 return;
770 if (!tok_jmp('~')) {
771 readpre();
772 ts_de(1);
773 o_uop(O_NOT);
774 return;
776 if (!tok_jmp(TOK2("++"))) {
777 inc_pre(O_ADD);
778 return;
780 if (!tok_jmp(TOK2("--"))) {
781 inc_pre(O_SUB);
782 return;
784 if (!tok_jmp(TOK_SIZEOF)) {
785 struct type t;
786 int op = !tok_jmp('(');
787 if (readtype(&t)) {
788 nogen++;
789 if (op)
790 readexpr();
791 else
792 readpre();
793 nogen--;
794 ts_pop(&t);
796 ts_push_bt(4);
797 o_num(type_totsz(&t));
798 if (op)
799 tok_expect(')');
800 return;
802 readpost();
805 static void readmul(void)
807 readpre();
808 while (1) {
809 if (!tok_jmp('*')) {
810 readpre();
811 ts_binop(O_MUL);
812 continue;
814 if (!tok_jmp('/')) {
815 readpre();
816 ts_binop(O_DIV);
817 continue;
819 if (!tok_jmp('%')) {
820 readpre();
821 ts_binop(O_MOD);
822 continue;
824 break;
828 static void readadd(void)
830 readmul();
831 while (1) {
832 if (!tok_jmp('+')) {
833 readmul();
834 ts_addop(O_ADD);
835 continue;
837 if (!tok_jmp('-')) {
838 readmul();
839 ts_addop(O_SUB);
840 continue;
842 break;
846 static void shift(int op)
848 struct type t;
849 readadd();
850 ts_pop_de2(NULL, &t);
851 o_bop(op | (BT_SIGNED & TYPE_BT(&t) ? O_SIGNED : 0));
852 ts_push_bt(TYPE_BT(&t));
855 static void readshift(void)
857 readadd();
858 while (1) {
859 if (!tok_jmp(TOK2("<<"))) {
860 shift(O_SHL);
861 continue;
863 if (!tok_jmp(TOK2(">>"))) {
864 shift(O_SHR);
865 continue;
867 break;
871 static void cmp(int op)
873 struct type t1, t2;
874 int bt;
875 readshift();
876 ts_pop_de2(&t1, &t2);
877 bt = bt_op(TYPE_BT(&t1), TYPE_BT(&t2));
878 o_bop(op | (bt & BT_SIGNED ? O_SIGNED : 0));
879 ts_push_bt(4 | BT_SIGNED);
882 static void readcmp(void)
884 readshift();
885 while (1) {
886 if (!tok_jmp('<')) {
887 cmp(O_LT);
888 continue;
890 if (!tok_jmp('>')) {
891 cmp(O_GT);
892 continue;
894 if (!tok_jmp(TOK2("<="))) {
895 cmp(O_LE);
896 continue;
898 if (!tok_jmp(TOK2(">="))) {
899 cmp(O_GE);
900 continue;
902 break;
906 static void eq(int op)
908 readcmp();
909 ts_pop_de2(NULL, NULL);
910 o_bop(op);
911 ts_push_bt(4 | BT_SIGNED);
914 static void readeq(void)
916 readcmp();
917 while (1) {
918 if (!tok_jmp(TOK2("=="))) {
919 eq(O_EQ);
920 continue;
922 if (!tok_jmp(TOK2("!="))) {
923 eq(O_NEQ);
924 continue;
926 break;
930 static void readbitand(void)
932 readeq();
933 while (!tok_jmp('&')) {
934 readeq();
935 ts_binop(O_AND);
939 static void readxor(void)
941 readbitand();
942 while (!tok_jmp('^')) {
943 readbitand();
944 ts_binop(O_XOR);
948 static void readbitor(void)
950 readxor();
951 while (!tok_jmp('|')) {
952 readxor();
953 ts_binop(O_OR);
957 #define MAXCOND (1 << 7)
959 static void readand(void)
961 int l_out = LABEL();
962 int l_fail = LABEL();
963 readbitor();
964 if (tok_see() != TOK2("&&"))
965 return;
966 o_fork();
967 ts_pop_de(NULL);
968 o_jz(l_fail);
969 while (!tok_jmp(TOK2("&&"))) {
970 readbitor();
971 ts_pop_de(NULL);
972 o_jz(l_fail);
974 o_num(1);
975 o_forkpush();
976 o_jmp(l_out);
977 o_label(l_fail);
978 o_num(0);
979 o_forkpush();
980 o_forkjoin();
981 o_label(l_out);
982 ts_push_bt(4 | BT_SIGNED);
985 static void reador(void)
987 int l_pass = LABEL();
988 int l_end = LABEL();
989 readand();
990 if (tok_see() != TOK2("||"))
991 return;
992 o_fork();
993 ts_pop_de(NULL);
994 o_jnz(l_pass);
995 while (!tok_jmp(TOK2("||"))) {
996 readand();
997 ts_pop_de(NULL);
998 o_jnz(l_pass);
1000 o_num(0);
1001 o_forkpush();
1002 o_jmp(l_end);
1003 o_label(l_pass);
1004 o_num(1);
1005 o_forkpush();
1006 o_forkjoin();
1007 o_label(l_end);
1008 ts_push_bt(4 | BT_SIGNED);
1011 static void readcexpr(void);
1013 static int readcexpr_const(void)
1015 long c;
1016 if (o_popnum(&c))
1017 return -1;
1018 if (!c)
1019 nogen++;
1020 readcexpr();
1021 /* both branches yield the same type; so ignore the first */
1022 ts_pop_de(NULL);
1023 tok_expect(':');
1024 if (c)
1025 nogen++;
1026 else
1027 nogen--;
1028 readcexpr();
1029 /* making sure t->addr == 0 on both branches */
1030 ts_de(1);
1031 if (c)
1032 nogen--;
1033 return 0;
1036 static void readcexpr(void)
1038 reador();
1039 if (tok_jmp('?'))
1040 return;
1041 ncexpr++;
1042 ts_pop_de(NULL);
1043 o_fork();
1044 if (readcexpr_const()) {
1045 int l_fail = LABEL();
1046 int l_end = LABEL();
1047 struct type ret;
1048 o_jz(l_fail);
1049 readcexpr();
1050 /* both branches yield the same type; so ignore the first */
1051 ts_pop_de(&ret);
1052 if (!TYPE_VOID(&ret))
1053 o_forkpush();
1054 o_jmp(l_end);
1056 tok_expect(':');
1057 o_label(l_fail);
1058 readcexpr();
1059 /* making sure t->addr == 0 on both branches */
1060 ts_de(1);
1061 if (!TYPE_VOID(&ret)) {
1062 o_forkpush();
1063 o_forkjoin();
1065 o_label(l_end);
1067 ncexpr--;
1070 static void opassign(int op, int ptrop)
1072 struct type t = ts[nts - 1];
1073 o_tmpcopy();
1074 ts_push(&t);
1075 readexpr();
1076 ts_addop(op);
1077 o_assign(TYPE_BT(&ts[nts - 2]));
1078 ts_pop(NULL);
1079 ts_de(0);
1082 static void doassign(void)
1084 struct type t = ts[nts - 1];
1085 if (!t.ptr && t.flags & T_STRUCT) {
1086 ts_pop(NULL);
1087 o_num(type_totsz(&t));
1088 o_memcpy();
1089 } else {
1090 ts_pop_de(NULL);
1091 o_assign(TYPE_BT(&ts[nts - 1]));
1092 ts_de(0);
1096 static void readexpr(void)
1098 readcexpr();
1099 if (!tok_jmp('=')) {
1100 readexpr();
1101 doassign();
1102 return;
1104 if (!tok_jmp(TOK2("+="))) {
1105 opassign(O_ADD, 1);
1106 return;
1108 if (!tok_jmp(TOK2("-="))) {
1109 opassign(O_SUB, 1);
1110 return;
1112 if (!tok_jmp(TOK2("*="))) {
1113 opassign(O_MUL, 0);
1114 return;
1116 if (!tok_jmp(TOK2("/="))) {
1117 opassign(O_DIV, 0);
1118 return;
1120 if (!tok_jmp(TOK2("%="))) {
1121 opassign(O_MOD, 0);
1122 return;
1124 if (!tok_jmp(TOK3("<<="))) {
1125 opassign(O_SHL, 0);
1126 return;
1128 if (!tok_jmp(TOK3(">>="))) {
1129 opassign(O_SHR, 0);
1130 return;
1132 if (!tok_jmp(TOK3("&="))) {
1133 opassign(O_AND, 0);
1134 return;
1136 if (!tok_jmp(TOK3("|="))) {
1137 opassign(O_OR, 0);
1138 return;
1140 if (!tok_jmp(TOK3("^="))) {
1141 opassign(O_XOR, 0);
1142 return;
1146 static void readestmt(void)
1148 do {
1149 o_tmpdrop(-1);
1150 nts = 0;
1151 readexpr();
1152 } while (!tok_jmp(','));
1155 #define F_GLOBAL(flags) (!((flags) & F_STATIC))
1157 static void globalinit(void *obj, int off, struct type *t)
1159 struct name *name = obj;
1160 char *elfname = *name->elfname ? name->elfname : name->name;
1161 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1162 struct type *t_de = &arrays[t->id].type;
1163 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1164 char buf[BUFSIZE];
1165 int len;
1166 tok_expect(TOK_STR);
1167 len = tok_str(buf);
1168 memcpy((void *) name->addr + off, buf, len);
1169 return;
1172 readexpr();
1173 o_datset(elfname, off, TYPE_BT(t));
1174 ts_pop(NULL);
1177 static void readfunc(struct name *name, int flags);
1179 static void globaldef(void *data, struct name *name, unsigned flags)
1181 struct type *t = &name->type;
1182 char *elfname = *name->elfname ? name->elfname : name->name;
1183 int sz;
1184 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1185 if (~flags & F_EXTERN)
1186 arrays[t->id].n = initsize();
1187 sz = type_totsz(t);
1188 if (!(flags & F_EXTERN) && (!(t->flags & T_FUNC) || t->ptr)) {
1189 if (tok_see() == '=')
1190 name->addr = (long) o_mkdat(elfname, sz, F_GLOBAL(flags));
1191 else
1192 o_mkbss(elfname, sz, F_GLOBAL(flags));
1194 global_add(name);
1195 if (!tok_jmp('='))
1196 initexpr(t, 0, name, globalinit);
1197 if (tok_see() == '{' && name->type.flags & T_FUNC)
1198 readfunc(name, flags);
1201 /* generate the address of local + off */
1202 static void o_localoff(long addr, int off)
1204 o_local(addr);
1205 if (off) {
1206 o_num(off);
1207 o_bop(O_ADD);
1211 static void localinit(void *obj, int off, struct type *t)
1213 long addr = *(long *) obj;
1214 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1215 struct type *t_de = &arrays[t->id].type;
1216 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1217 char buf[BUFSIZE];
1218 int len;
1219 tok_expect(TOK_STR);
1220 len = tok_str(buf);
1221 o_localoff(addr, off);
1222 o_sym(tmp_str(buf, len));
1223 o_num(len);
1224 o_memcpy();
1225 o_tmpdrop(1);
1226 return;
1229 o_localoff(addr, off);
1230 ts_push(t);
1231 readexpr();
1232 doassign();
1233 ts_pop(NULL);
1234 o_tmpdrop(1);
1237 /* current function name */
1238 static char func_name[NAMELEN];
1240 static void localdef(void *data, struct name *name, unsigned flags)
1242 struct type *t = &name->type;
1243 if ((flags & F_EXTERN) || ((t->flags & T_FUNC) && !t->ptr)) {
1244 global_add(name);
1245 return;
1247 if (flags & F_STATIC) {
1248 sprintf(name->elfname, "__neatcc.%s.%s", func_name, name->name);
1249 globaldef(data, name, flags);
1250 return;
1252 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1253 arrays[t->id].n = initsize();
1254 name->addr = o_mklocal(type_totsz(&name->type));
1255 local_add(name);
1256 if (!tok_jmp('=')) {
1257 if (t->flags & (T_ARRAY | T_STRUCT) && !t->ptr) {
1258 o_local(name->addr);
1259 o_num(0);
1260 o_num(type_totsz(t));
1261 o_memset();
1262 o_tmpdrop(1);
1264 initexpr(t, 0, &name->addr, localinit);
1268 static void typedefdef(void *data, struct name *name, unsigned flags)
1270 typedef_add(name->name, &name->type);
1273 static void readstmt(void);
1275 #define MAXCASES (1 << 7)
1277 static void readswitch(void)
1279 int o_break = l_break;
1280 long val_addr = o_mklocal(LONGSZ);
1281 struct type t;
1282 int ncases = 0; /* number of case labels */
1283 int l_failed = LABEL(); /* address of last failed jmp */
1284 int l_matched = LABEL(); /* address of last walk through jmp */
1285 int l_default = 0; /* default case label */
1286 l_break = LABEL();
1287 tok_expect('(');
1288 readexpr();
1289 ts_pop_de(&t);
1290 o_local(val_addr);
1291 o_tmpswap();
1292 o_assign(TYPE_BT(&t));
1293 ts_de(0);
1294 o_tmpdrop(1);
1295 tok_expect(')');
1296 tok_expect('{');
1297 while (tok_jmp('}')) {
1298 if (tok_see() != TOK_CASE && tok_see() != TOK_DEFAULT) {
1299 readstmt();
1300 continue;
1302 if (ncases)
1303 o_jmp(l_matched);
1304 if (tok_get() == TOK_CASE) {
1305 o_label(l_failed);
1306 l_failed = LABEL();
1307 caseexpr = 1;
1308 readexpr();
1309 ts_pop_de(NULL);
1310 caseexpr = 0;
1311 o_local(val_addr);
1312 o_deref(TYPE_BT(&t));
1313 o_bop(O_EQ);
1314 o_jz(l_failed);
1315 o_tmpdrop(1);
1316 } else {
1317 if (!ncases)
1318 o_jmp(l_failed);
1319 l_default = LABEL();
1320 o_label(l_default);
1322 tok_expect(':');
1323 o_label(l_matched);
1324 l_matched = LABEL();
1325 ncases++;
1327 o_rmlocal(val_addr, LONGSZ);
1328 o_jmp(l_break);
1329 o_label(l_failed);
1330 if (l_default)
1331 o_jmp(l_default);
1332 o_label(l_break);
1333 l_break = o_break;
1336 #define MAXLABELS (1 << 10)
1338 static char label_name[MAXLABELS][NAMELEN];
1339 static int label_ids[MAXLABELS];
1340 static int nlabels;
1342 static int label_id(char *name)
1344 int i;
1345 for (i = nlabels - 1; i >= 0; --i)
1346 if (!strcmp(label_name[i], name))
1347 return label_ids[i];
1348 strcpy(label_name[nlabels], name);
1349 label_ids[nlabels] = LABEL();
1350 return label_ids[nlabels++];
1353 static void readstmt(void)
1355 o_tmpdrop(-1);
1356 nts = 0;
1357 if (!tok_jmp('{')) {
1358 int _nlocals = nlocals;
1359 int _nglobals = nglobals;
1360 int _nenums = nenums;
1361 int _ntypedefs = ntypedefs;
1362 int _nstructs = nstructs;
1363 int _nfuncs = nfuncs;
1364 int _narrays = narrays;
1365 while (tok_jmp('}'))
1366 readstmt();
1367 nlocals = _nlocals;
1368 nenums = _nenums;
1369 ntypedefs = _ntypedefs;
1370 nstructs = _nstructs;
1371 nfuncs = _nfuncs;
1372 narrays = _narrays;
1373 nglobals = _nglobals;
1374 return;
1376 if (!readdefs(localdef, NULL)) {
1377 tok_expect(';');
1378 return;
1380 if (!tok_jmp(TOK_TYPEDEF)) {
1381 readdefs(typedefdef, NULL);
1382 tok_expect(';');
1383 return;
1385 if (!tok_jmp(TOK_IF)) {
1386 int l_fail = LABEL();
1387 int l_end = LABEL();
1388 tok_expect('(');
1389 readexpr();
1390 tok_expect(')');
1391 ts_pop_de(NULL);
1392 o_jz(l_fail);
1393 readstmt();
1394 if (!tok_jmp(TOK_ELSE)) {
1395 o_jmp(l_end);
1396 o_label(l_fail);
1397 readstmt();
1398 o_label(l_end);
1399 } else {
1400 o_label(l_fail);
1402 return;
1404 if (!tok_jmp(TOK_WHILE)) {
1405 int o_break = l_break;
1406 int o_cont = l_cont;
1407 l_break = LABEL();
1408 l_cont = LABEL();
1409 o_label(l_cont);
1410 tok_expect('(');
1411 readexpr();
1412 tok_expect(')');
1413 ts_pop_de(NULL);
1414 o_jz(l_break);
1415 readstmt();
1416 o_jmp(l_cont);
1417 o_label(l_break);
1418 l_break = o_break;
1419 l_cont = o_cont;
1420 return;
1422 if (!tok_jmp(TOK_DO)) {
1423 int o_break = l_break;
1424 int o_cont = l_cont;
1425 int l_beg = LABEL();
1426 l_break = LABEL();
1427 l_cont = LABEL();
1428 o_label(l_beg);
1429 readstmt();
1430 tok_expect(TOK_WHILE);
1431 tok_expect('(');
1432 o_label(l_cont);
1433 readexpr();
1434 ts_pop_de(NULL);
1435 o_jnz(l_beg);
1436 tok_expect(')');
1437 o_label(l_break);
1438 tok_expect(';');
1439 l_break = o_break;
1440 l_cont = o_cont;
1441 return;
1443 if (!tok_jmp(TOK_FOR)) {
1444 int o_break = l_break;
1445 int o_cont = l_cont;
1446 int l_check = LABEL(); /* for condition label */
1447 int l_body = LABEL(); /* for block label */
1448 l_cont = LABEL();
1449 l_break = LABEL();
1450 tok_expect('(');
1451 if (tok_see() != ';')
1452 readestmt();
1453 tok_expect(';');
1454 o_label(l_check);
1455 if (tok_see() != ';') {
1456 readestmt();
1457 ts_pop_de(NULL);
1458 o_jz(l_break);
1460 tok_expect(';');
1461 o_jmp(l_body);
1462 o_label(l_cont);
1463 if (tok_see() != ')')
1464 readestmt();
1465 tok_expect(')');
1466 o_jmp(l_check);
1467 o_label(l_body);
1468 readstmt();
1469 o_jmp(l_cont);
1470 o_label(l_break);
1471 l_break = o_break;
1472 l_cont = o_cont;
1473 return;
1475 if (!tok_jmp(TOK_SWITCH)) {
1476 readswitch();
1477 return;
1479 if (!tok_jmp(TOK_RETURN)) {
1480 int ret = tok_see() != ';';
1481 if (ret) {
1482 readexpr();
1483 ts_pop_de(NULL);
1485 tok_expect(';');
1486 o_ret(ret);
1487 return;
1489 if (!tok_jmp(TOK_BREAK)) {
1490 tok_expect(';');
1491 o_jmp(l_break);
1492 return;
1494 if (!tok_jmp(TOK_CONTINUE)) {
1495 tok_expect(';');
1496 o_jmp(l_cont);
1497 return;
1499 if (!tok_jmp(TOK_GOTO)) {
1500 tok_expect(TOK_NAME);
1501 o_jmp(label_id(tok_id()));
1502 tok_expect(';');
1503 return;
1505 readestmt();
1506 /* labels */
1507 if (!tok_jmp(':')) {
1508 o_label(label_id(tok_id()));
1509 return;
1511 tok_expect(';');
1514 static void readfunc(struct name *name, int flags)
1516 struct funcinfo *fi = &funcs[name->type.id];
1517 long beg = tok_addr();
1518 int i;
1519 strcpy(func_name, fi->name);
1520 o_func_beg(func_name, fi->nargs, F_GLOBAL(flags), fi->varg);
1521 for (i = 0; i < fi->nargs; i++) {
1522 struct name arg = {"", "", fi->args[i], o_arg2loc(i)};
1523 strcpy(arg.name, fi->argnames[i]);
1524 local_add(&arg);
1526 /* first pass: collecting statistics */
1527 o_pass1();
1528 readstmt();
1529 tok_jump(beg);
1530 /* second pass: generating code */
1531 o_pass2();
1532 readstmt();
1533 o_func_end();
1534 func_name[0] = '\0';
1535 nlocals = 0;
1536 label = 0;
1537 nlabels = 0;
1540 static void readdecl(void)
1542 if (!tok_jmp(TOK_TYPEDEF)) {
1543 readdefs(typedefdef, NULL);
1544 tok_expect(';');
1545 return;
1547 readdefs_int(globaldef, NULL);
1548 tok_jmp(';');
1551 static void parse(void)
1553 while (tok_see() != TOK_EOF)
1554 readdecl();
1557 static void compat_macros(void)
1559 cpp_define("__STDC__", "");
1560 cpp_define("__linux__", "");
1561 cpp_define(I_ARCH, "");
1563 /* ignored keywords */
1564 cpp_define("const", "");
1565 cpp_define("register", "");
1566 cpp_define("volatile", "");
1567 cpp_define("inline", "");
1568 cpp_define("restrict", "");
1569 cpp_define("__inline__", "");
1570 cpp_define("__restrict__", "");
1571 cpp_define("__attribute__(x)", "");
1572 cpp_define("__builtin_va_list__", "long");
1575 int main(int argc, char *argv[])
1577 char obj[128] = "";
1578 int ofd;
1579 int i = 1;
1580 compat_macros();
1581 while (i < argc && argv[i][0] == '-') {
1582 if (argv[i][1] == 'I')
1583 cpp_addpath(argv[i][2] ? argv[i] + 2 : argv[++i]);
1584 if (argv[i][1] == 'D') {
1585 char *name = argv[i] + 2;
1586 char *def = "";
1587 char *eq = strchr(name, '=');
1588 if (eq) {
1589 *eq = '\0';
1590 def = eq + 1;
1592 cpp_define(name, def);
1594 if (argv[i][1] == 'o')
1595 strcpy(obj, argv[i][2] ? argv[i] + 2 : argv[++i]);
1596 i++;
1598 if (i == argc)
1599 die("neatcc: no file given\n");
1600 if (cpp_init(argv[i]))
1601 die("neatcc: cannot open <%s>\n", argv[i]);
1602 parse();
1603 if (!*obj) {
1604 strcpy(obj, argv[i]);
1605 obj[strlen(obj) - 1] = 'o';
1607 ofd = open(obj, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1608 o_write(ofd);
1609 close(ofd);
1610 return 0;
1614 /* parsing function and variable declarations */
1616 /* read the base type of a variable */
1617 static int basetype(struct type *type, unsigned *flags)
1619 int sign = 1;
1620 int size = 4;
1621 int done = 0;
1622 int i = 0;
1623 int isunion;
1624 char name[NAMELEN] = "";
1625 *flags = 0;
1626 type->flags = 0;
1627 type->ptr = 0;
1628 type->addr = 0;
1629 while (!done) {
1630 switch (tok_see()) {
1631 case TOK_STATIC:
1632 *flags |= F_STATIC;
1633 break;
1634 case TOK_EXTERN:
1635 *flags |= F_EXTERN;
1636 break;
1637 case TOK_VOID:
1638 sign = 0;
1639 size = 0;
1640 done = 1;
1641 break;
1642 case TOK_INT:
1643 done = 1;
1644 break;
1645 case TOK_CHAR:
1646 size = 1;
1647 done = 1;
1648 break;
1649 case TOK_SHORT:
1650 size = 2;
1651 break;
1652 case TOK_LONG:
1653 size = LONGSZ;
1654 break;
1655 case TOK_SIGNED:
1656 break;
1657 case TOK_UNSIGNED:
1658 sign = 0;
1659 break;
1660 case TOK_UNION:
1661 case TOK_STRUCT:
1662 isunion = tok_get() == TOK_UNION;
1663 if (!tok_jmp(TOK_NAME))
1664 strcpy(name, tok_id());
1665 if (tok_see() == '{')
1666 type->id = struct_create(name, isunion);
1667 else
1668 type->id = struct_find(name, isunion);
1669 type->flags |= T_STRUCT;
1670 type->bt = LONGSZ;
1671 return 0;
1672 case TOK_ENUM:
1673 tok_get();
1674 tok_jmp(TOK_NAME);
1675 if (tok_see() == '{')
1676 enum_create();
1677 type->bt = 4 | BT_SIGNED;
1678 return 0;
1679 default:
1680 if (tok_see() == TOK_NAME) {
1681 int id = typedef_find(tok_id());
1682 if (id != -1) {
1683 tok_get();
1684 memcpy(type, &typedefs[id].type,
1685 sizeof(*type));
1686 return 0;
1689 if (!i)
1690 return 1;
1691 done = 1;
1692 continue;
1694 i++;
1695 tok_get();
1697 type->bt = size | (sign ? BT_SIGNED : 0);
1698 return 0;
1701 static void readptrs(struct type *type)
1703 while (!tok_jmp('*')) {
1704 type->ptr++;
1705 if (!type->bt)
1706 type->bt = 1;
1710 /* read function arguments */
1711 static int readargs(struct type *args, char argnames[][NAMELEN], int *varg)
1713 int nargs = 0;
1714 tok_expect('(');
1715 *varg = 0;
1716 while (tok_see() != ')') {
1717 if (!tok_jmp(TOK3("..."))) {
1718 *varg = 1;
1719 break;
1721 if (readname(&args[nargs], argnames[nargs], NULL)) {
1722 /* argument has no type, assume int */
1723 tok_expect(TOK_NAME);
1724 memset(&args[nargs], 0, sizeof(struct type));
1725 args[nargs].bt = 4 | BT_SIGNED;
1726 strcpy(argnames[nargs], tok_id());
1728 /* argument arrays are pointers */
1729 array2ptr(&args[nargs]);
1730 nargs++;
1731 if (tok_jmp(','))
1732 break;
1734 tok_expect(')');
1735 /* void argument */
1736 if (nargs == 1 && !TYPE_BT(&args[0]))
1737 return 0;
1738 return nargs;
1741 /* read K&R function arguments */
1742 static void krdef(void *data, struct name *name, unsigned flags)
1744 struct funcinfo *fi = data;
1745 int i;
1746 for (i = 0; i < fi->nargs; i++)
1747 if (!strcmp(fi->argnames[i], name->name))
1748 memcpy(&fi->args[i], &name->type, sizeof(name->type));
1752 * readarrays() parses array specifiers when reading a definition in
1753 * readname(). The "type" parameter contains the type contained in the
1754 * inner array; for instance, type in "int *a[10][20]" would be an int
1755 * pointer. When returning, the "type" parameter is changed to point
1756 * to the final array. The function returns a pointer to the type in
1757 * the inner array; this is useful when the type is not complete yet,
1758 * like when creating an array of function pointers as in
1759 * "int (*f[10])(int)". If there is no array brackets, NULL is returned.
1761 static struct type *readarrays(struct type *type)
1763 long arsz[16];
1764 struct type *inner = NULL;
1765 int nar = 0;
1766 int i;
1767 while (!tok_jmp('[')) {
1768 long n = 0;
1769 if (tok_jmp(']')) {
1770 readexpr();
1771 ts_pop_de(NULL);
1772 if (o_popnum(&n))
1773 err("const expr expected\n");
1774 tok_expect(']');
1776 arsz[nar++] = n;
1778 for (i = nar - 1; i >= 0; i--) {
1779 type->id = array_add(type, arsz[i]);
1780 if (!inner)
1781 inner = &arrays[type->id].type;
1782 type->flags = T_ARRAY;
1783 type->bt = LONGSZ;
1784 type->ptr = 0;
1786 return inner;
1790 * readname() reads a variable definition; the name is copied into
1791 * "name" and the type is copied into "main" argument. The "base"
1792 * argument, if not NULL, indicates the base type of the variable.
1793 * For instance, the base type of "a" and "b" in "int *a, b[10]" is
1794 * "int". If NULL, basetype() is called directly to read the base
1795 * type of the variable. readname() returns zero, only if the
1796 * variable can be read.
1798 static int readname(struct type *main, char *name, struct type *base)
1800 struct type tpool[3];
1801 int npool = 0;
1802 struct type *type = &tpool[npool++];
1803 struct type *ptype = NULL; /* type inside parenthesis */
1804 struct type *btype = NULL; /* type before parenthesis */
1805 struct type *inner;
1806 unsigned flags;
1807 memset(tpool, 0, sizeof(tpool));
1808 if (name)
1809 *name = '\0';
1810 if (!base) {
1811 if (basetype(type, &flags))
1812 return 1;
1813 } else {
1814 memcpy(type, base, sizeof(*base));
1816 readptrs(type);
1817 if (!tok_jmp('(')) {
1818 btype = type;
1819 type = &tpool[npool++];
1820 ptype = type;
1821 readptrs(type);
1823 if (!tok_jmp(TOK_NAME) && name)
1824 strcpy(name, tok_id());
1825 inner = readarrays(type);
1826 if (ptype && inner)
1827 ptype = inner;
1828 if (ptype)
1829 tok_expect(')');
1830 if (tok_see() == '(') {
1831 struct type args[MAXARGS];
1832 char argnames[MAXARGS][NAMELEN];
1833 int varg = 0;
1834 int nargs = readargs(args, argnames, &varg);
1835 if (!ptype) {
1836 btype = type;
1837 type = &tpool[npool++];
1838 ptype = type;
1840 ptype->flags = T_FUNC;
1841 ptype->bt = LONGSZ;
1842 ptype->id = func_create(btype, name, argnames, args, nargs, varg);
1843 if (tok_see() != ';')
1844 while (tok_see() != '{' && !readdefs(krdef, &funcs[ptype->id]))
1845 tok_expect(';');
1846 } else {
1847 if (ptype && readarrays(type))
1848 array2ptr(type);
1850 memcpy(main, type, sizeof(*type));
1851 return 0;
1854 static int readtype(struct type *type)
1856 return readname(type, NULL, NULL);
1860 * readdef() reads a variable definitions statement. The definition
1861 * statement can appear in anywhere: global variables, function
1862 * local variables, struct fields, and typedefs. For each defined
1863 * variable, def() callback is called with the appropriate name
1864 * struct and flags; the callback should finish parsing the definition
1865 * by possibly reading the initializer expression and saving the name
1866 * struct.
1868 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
1869 void *data)
1871 struct type base;
1872 unsigned base_flags;
1873 if (basetype(&base, &base_flags))
1874 return 1;
1875 if (tok_see() == ';' || tok_see() == '{')
1876 return 0;
1877 do {
1878 struct name name = {{""}};
1879 if (readname(&name.type, name.name, &base))
1880 break;
1881 def(data, &name, base_flags);
1882 } while (!tok_jmp(','));
1883 return 0;
1886 /* just like readdefs, but default to int type; for handling K&R functions */
1887 static int readdefs_int(void (*def)(void *data, struct name *name, unsigned flags),
1888 void *data)
1890 struct type base;
1891 unsigned flags = 0;
1892 if (basetype(&base, &flags)) {
1893 if (tok_see() != TOK_NAME)
1894 return 1;
1895 memset(&base, 0, sizeof(base));
1896 base.bt = 4 | BT_SIGNED;
1898 if (tok_see() != ';') {
1899 do {
1900 struct name name = {{""}};
1901 if (readname(&name.type, name.name, &base))
1902 break;
1903 def(data, &name, flags);
1904 } while (!tok_jmp(','));
1906 return 0;
1910 /* parsing initializer expressions */
1912 static void jumpbrace(void)
1914 int depth = 0;
1915 while (tok_see() != '}' || depth--)
1916 if (tok_get() == '{')
1917 depth++;
1918 tok_expect('}');
1921 /* compute the size of the initializer expression */
1922 static int initsize(void)
1924 long addr = tok_addr();
1925 int n = 0;
1926 if (tok_jmp('='))
1927 return 0;
1928 if (!tok_jmp(TOK_STR)) {
1929 n = tok_str(NULL);
1930 tok_jump(addr);
1931 return n;
1933 tok_expect('{');
1934 while (tok_jmp('}')) {
1935 long idx = n;
1936 if (!tok_jmp('[')) {
1937 readexpr();
1938 ts_pop_de(NULL);
1939 o_popnum(&idx);
1940 tok_expect(']');
1941 tok_expect('=');
1943 if (n < idx + 1)
1944 n = idx + 1;
1945 while (tok_see() != '}' && tok_see() != ',')
1946 if (tok_get() == '{')
1947 jumpbrace();
1948 tok_jmp(',');
1950 tok_jump(addr);
1951 return n;
1954 static struct type *innertype(struct type *t)
1956 if (t->flags & T_ARRAY && !t->ptr)
1957 return innertype(&arrays[t->id].type);
1958 return t;
1961 /* read the initializer expression and initialize basic types using set() cb */
1962 static void initexpr(struct type *t, int off, void *obj,
1963 void (*set)(void *obj, int off, struct type *t))
1965 if (tok_jmp('{')) {
1966 set(obj, off, t);
1967 return;
1969 if (!t->ptr && t->flags & T_STRUCT) {
1970 struct structinfo *si = &structs[t->id];
1971 int i;
1972 for (i = 0; i < si->nfields && tok_see() != '}'; i++) {
1973 struct name *field = &si->fields[i];
1974 if (!tok_jmp('.')) {
1975 tok_expect(TOK_NAME);
1976 field = struct_field(t->id, tok_id());
1977 tok_expect('=');
1979 initexpr(&field->type, off + field->addr, obj, set);
1980 if (tok_jmp(','))
1981 break;
1983 } else if (t->flags & T_ARRAY) {
1984 struct type *t_de = &arrays[t->id].type;
1985 int i;
1986 /* handling extra braces as in: char s[] = {"sth"} */
1987 if (TYPE_SZ(t_de) == 1 && tok_see() == TOK_STR) {
1988 set(obj, off, t);
1989 tok_expect('}');
1990 return;
1992 for (i = 0; tok_see() != '}'; i++) {
1993 long idx = i;
1994 struct type *it = t_de;
1995 if (!tok_jmp('[')) {
1996 readexpr();
1997 ts_pop_de(NULL);
1998 o_popnum(&idx);
1999 tok_expect(']');
2000 tok_expect('=');
2002 if (tok_see() != '{' && (tok_see() != TOK_STR ||
2003 !(it->flags & T_ARRAY)))
2004 it = innertype(t_de);
2005 initexpr(it, off + type_totsz(it) * idx, obj, set);
2006 if (tok_jmp(','))
2007 break;
2010 tok_expect('}');