/*
 * 68K/386 32-bit C compiler.
 *
 * copyright (c) 1997, David Lindauer
 * 
 * This compiler is intended for educational use.  It may not be used
 * for profit without the express written consent of the author.
 *
 * It may be freely redistributed, as long as this notice remains intact
 * and either the original sources or derived sources 
 * are distributed along with any executables derived from the originals.
 *
 * The author is not responsible for any damages that may arise from use
 * of this software, either idirect or consequential.
 *
 * V1.85 July 2000
 * David Lindauer, camille@bluegrass.net
 *
 * Credits to Mathew Brandt for original K&R C compiler
 *
 */
/*
 * handles initialization of module-scoped declarations
 */
#include        <stdio.h>
#include				<limits.h>
#include				<string.h>
#include        "lists.h"
#include        "expr.h"
#include        "c.h"
#include        "errors.h"
#include				"lists.h"

extern int stdldoublesize;
extern enum e_sym lastst;
extern char lastid[], laststr[];
extern int skm_declend[];
extern int nextlabel;
extern TYP stdmatch;
extern int skm_declclosepa[];
extern int skm_closebr[];
extern int prm_cplusplus;
extern SYM *currentfunc;
extern int prm_bss;
extern int laststrlen;
extern LIST *varlisthead,*varlisttail;
extern int stdmemberptrsize;
extern SYM *typequal;

long bittab[32] = { 1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
			0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
			0x1ffffL,0x3ffffL,0x7ffffL,0xfffffL,0x1fffffL,0x3fffffL,0x7fffffL,0xffffffL,
			0x1ffffffL,0x3ffffffL,0x7ffffffL,0xfffffffL,0x1fffffffL,0x3fffffffL,0x7fffffffL,0xffffffffL
};

static SYM *locsp;
static short cursize;
static short startbit,bits;
static long totbits;
static int allocated;
static ENODE *cpprefhead;
static ENODE **cppreftail;
static int baseoffs = 0;

static struct decldata **sptr;

static struct declares {
		struct declares *link;
		SYM *sp;
} *declarations, *decltail;
	
static long gen(SYM *sp);

void initini(void)
{
	cpprefhead = 0;
	declarations = decltail = 0;
}
void initrundown(void)
/*
 * Dump out C++ pointer and reference initializations functions 
 *
 * also dump out local vars
 *
 */
{
	int first;
	struct declares *q;
	long nbytes,obytes,val,onbytes;

#ifdef CPLUSPLUS
	if (cpprefhead) {
		int lbl = nextlabel++;
		SNODE stmt;
		varlisthead = varlisttail = 0;
		currentfunc = xalloc(sizeof(SYM));
		currentfunc->tp = maketype(bt_func,0);
		currentfunc->tp->btp = maketype(bt_void,0);
		currentfunc->tp->lst.head = 0;
		currentfunc->intflag = 0;
		currentfunc->name = "__CPP_INIT_FUNC__";
		stmt.stype = st_expr;
		stmt.next = 0;
		stmt.exp = cpprefhead;
		cseg();
	
		genfunc(&stmt);
#ifdef ICODE
		rewrite_icode();
#else
		flush_peep();
#endif
		cppseg();
		genref(currentfunc,0);
		currentfunc = 0;
		cpprefhead = 0;
	}
#endif
	q = declarations;
	nbytes = 0;
	first = TRUE;
	while (q) {
		SYM *sp = q->sp;
		if (first) {
			nl();
			dseg();
		}
		first = FALSE;
		if ((sp->init || !prm_bss) && !sp->absflag) {
			int align = getalign(sc_global,sp->tp);
			val = align - (nbytes % align);
			if (val != align) {
				genstorage(val);
				nbytes += val;
				nl();
			}
			onbytes = nbytes;
			nbytes += gen(sp);
			sp->value.i = onbytes;
		}
		q = q->link;
	}
	first = TRUE;
	if (prm_bss) {
		obytes  = nbytes;
		nbytes = 0;
		q = declarations;
		while (q) {
			SYM *sp = q->sp;
			if (first) {
				nl();
				bssseg();
			}
			first = FALSE;
			if (!sp->init && !sp->absflag) {
				int align = getalign(sc_global,sp->tp);
				val = align - (nbytes % align);
				if (val != align) {
					genstorage(val);
					nbytes += val;
					nl();
				}
			onbytes = nbytes;
			nbytes += gen(sp);
			sp->value.i = onbytes + obytes;
			}
			q = q->link;
		}
	}
}
static long gen(SYM *sp)
{
		struct decldata *decldata = sp->init;
		long nbytes=0;
		if (sp->storage_class == sc_global) {
			globaldef(sp);
		}
		if (sp->staticlabel)
			put_staticlabel(sp->value.i);
		else
			gen_strlab(sp);
		if (decldata) {
			while (decldata) {
				switch (decldata->mode) {
					case dd_byte: 
						genbyte(decldata->val.i);
						nbytes++;;
						break;
					case dd_word:
						genword(decldata->val.i);
						nbytes += 2;
						break;
					case dd_long:
						genlong(decldata->val.i);
						nbytes += 4;
						break;
					case dd_float:
						genfloat(decldata->val.f);
						nbytes += 4;
						break;
					case dd_double:
						gendouble(decldata->val.f);
						nbytes += 8;
						break;
					case dd_ldouble:
						genlongdouble(decldata->val.f);
						nbytes += stdldoublesize;
						break;
					case dd_pcname:
						genpcref(decldata->val.sp,decldata->offset);
						nbytes += 4;
						break;
					case dd_dataname:
						genref(decldata->val.sp,decldata->offset);
						nbytes += 4;
						break;
					case dd_storage:
						genstorage(decldata->val.i);
						nbytes += decldata->val.i;
						break;
					case dd_label:
						gen_labref(decldata->val.i);
						nbytes += 4;
						break;
				}
				decldata = decldata->link;
			}
		}
		else {
			if (sp->tp->size == 0)
				gensymerror(ERR_ZEROSTORAGE,sp->name);
			else
				genstorage(nbytes += sp->tp->size);
		}
	nl();
	return nbytes;
}
#ifdef CPLUSPLUS
void cppinitinsert(ENODE *node)
/*
 * insert an initialization function on the list
 */
{
	if (!cpprefhead) {
		cpprefhead = node;
		cppreftail = &cpprefhead;
	}
	else {
		*cppreftail = makenode(en_void,*cppreftail,node);
		cppreftail = & (*cppreftail)->v.p[1];
	}
}
#endif
void insert_decl_sp(SYM *sp)
{		
				 	struct declares * p = xalloc(sizeof(struct declares));
					p -> sp = sp;
					p->link = 0;
					if (declarations)
						decltail = decltail->link = p;
					else
						decltail = declarations = p;
					sp->indecltable = TRUE;
}
int doinit(SYM *sp)
/*
 * Handle static variable initialize
 */
{   		int nbytes=0;
				typequal = 0;
				sp->tp->uflags |= UF_DEFINED;
				allocated = FALSE;
				baseoffs = 0;
				totbits = 0;
				cursize = -1;
				bits = -1;
				locsp = sp;
				sptr = &sp->init;
				if (!sp->indecltable) {
					insert_decl_sp(sp);
				}
#ifdef CPLUSPLUS
				if (sp->tp->type == bt_class) {
					ENODE *ep;
					basedecl(&ep,sp);
					if (ep)
						cppinitinsert(ep);
				}
        else 
#endif
				{
#ifdef CPLUSPLUS
					int opened = FALSE;
					if (prm_cplusplus && lastst == openpa) {
						opened = TRUE;
						lastst = assign;
					}
#endif
					if (lastst == assign) {
								getsym();
								if (sp->init)
									gensymerror(ERR_MULTIPLEINIT,sp->name);
								if (sp->absflag) {
									generror(ERR_NOINIT,0,skm_declend);
				          return nbytes;
								}
                nbytes = inittype(sp->tp);
								*sptr = 0;
          }
#ifdef CPLUSPLUS
					if (opened)
						needpunc(closepa,skm_declclosepa);
#endif
				}
        endinit();
				return nbytes;
}

int     inittype(TYP *tp)
/*
 * Init for basic types
 */
{       int     nbytes;
        switch(tp->type) {

								case bt_float:
												nbytes = initfloat();
												break;
								case bt_longdouble:
												nbytes = initlongdouble();
												break;
								case bt_double:
												nbytes = initdouble();
												break;
                case bt_bool:
                case bt_char:
                        nbytes = initchar();
                        break;
                case bt_unsignedchar:
                        nbytes = inituchar();
                        break;
                case bt_unsignedshort:
                        nbytes = initushort();
                        break;
                case bt_short:
                case bt_enum:
                        nbytes = initshort();
                        break;
                case bt_pointer:
												if (tp->btp->type == bt_func) {
                        	nbytes = initpointerfunc();
                        	break;
												} else if( tp->val_flag)
                                nbytes = initarray(tp);
                        else
                                nbytes = initpointer();
                        break;
#ifdef CPLUSPLUS
								case bt_ref:
												nbytes = initref(tp->btp);
												break;
#endif
                case bt_unsigned:
                        nbytes = initulong();
                        break;
                case bt_long:
                case bt_matchall:
                        nbytes = initlong();
                        break;
                case bt_struct:
                        nbytes = initstruct(tp);
                        break;
								case bt_union:
											 	nbytes = inittype(tp->lst.head->tp);
												break;
#ifdef CPLUSPLUS
								case bt_memberptr:
                        nbytes = initmemberptr(tp->btp, tp->sp);
												break;
#endif
                default:
  											gensymerror(ERR_NOINIT,locsp->name);
                        nbytes = 0;
                }
				baseoffs+=nbytes;
        return nbytes;
}

int initarray(TYP *tp)
/*
 * Init for arrays
 */
{       int     nbytes;
				int canpad = FALSE;
        char    *p;
				int needend = FALSE;
        nbytes = 0;
        if( lastst == begin) {
                getsym();               /* skip past the brace */
								needend = TRUE;
								if ((tp->btp->type == bt_char  || tp->btp->type ==bt_unsignedchar)&& lastst == sconst)
									goto grabchar;
								if ((tp->btp->type == bt_short  || tp->btp->type ==bt_unsignedshort)&& lastst == lsconst)
									goto grabchar;
                while(lastst != end && lastst != eof) {
                        nbytes += inittype(tp->btp);
                        if( lastst == comma)
                                getsym();
                        else if( lastst != end) {
                                expecttoken(end,0);
																break;
												}
                        }
                getsym();               /* skip closing brace */
                }
        else { 
grabchar:		
						allocated = TRUE;
						nbytes = 0;
						if ((tp->btp->type == bt_char  || tp->btp->type ==bt_unsignedchar)&& lastst == sconst) {
							canpad = TRUE;
							while (lastst == sconst) {
                p = laststr;
								while (laststrlen--) {
									nbytes++;
									agflush(1,*p++);
								}
                getsym();
							}
							if (needend)
								needpunc(end,skm_declend);
							agflush(1,0);
							nbytes++;
					  } else if ((tp->btp->type == bt_short  || tp->btp->type ==bt_unsignedshort)&& lastst == lsconst) {
							while (lastst == lsconst) {
                p = laststr;
								while (laststrlen--) {
									nbytes+=2;
									agflush(2,*p++);
								}
                getsym();
							}
							if (needend)
								needpunc(end,skm_declend);
							agflush(2,0);
							nbytes +=2;
            }
            else generror(ERR_PUNCT,semicolon,0);
				}
        if(nbytes < tp->size) {
								nl();
                makestorage( tp->size - nbytes);
								nbytes = tp->size;
				}
        else if (tp->size == 0)
					tp->size = nbytes;
				else if( nbytes > tp->size && (!canpad || nbytes > tp->size+1))
                generror(ERR_INITSIZE,0,0);    /* too many initializers */
        return nbytes;
}

int initstruct(TYP *tp)
/*
 * Init for structures
 */
{       SYM     *sp;
        int     nbytes;
        needpunc(begin,0);
        nbytes = 0;
        sp = tp->lst.head;      /* start at top of symbol table */
        while(sp != 0 && lastst != end && lastst != eof) {
								startbit = sp->tp->startbit;
								bits = sp->tp->bits;
								if (nbytes < sp->value.i)
									makestorage(sp->value.i - nbytes);
								nbytes = sp->value.i;
                nbytes += inittype(sp->tp);
                if( lastst == comma)
                        getsym();
                else if(lastst == end)
                        break;
                else
                        expecttoken(end,0);
                sp = sp->next;
                }
				nbytes += agbits(-1,0);
        if( nbytes < tp->size) {
					makestorage(tp->size - nbytes);
				}
        needpunc(end,skm_declend);
        return tp->size;
}

int makelabel(void)
{
	struct decldata *q = *sptr = xalloc(sizeof(struct decldata));
	q->val.i = tostring();
	sptr = &(*sptr)->link;
	q->mode = dd_label;
	return q->val.i;
}
int makeref(int ispc, SYM *sp)
{
	struct decldata *q = *sptr = xalloc(sizeof(struct decldata));
	sp->extflag = TRUE;
	q->val.sp = sp;
	q->offset = 0;
	sptr = &(*sptr)->link;
	q->mode = ispc ? dd_pcname : dd_dataname;
}
int makestorage(long val)
{
	struct decldata *q = *sptr = xalloc(sizeof(struct decldata));
	q->val.i = val;
	sptr = &(*sptr)->link;
	q->mode = dd_storage;
}
int agflush(int size, long val)
/*
 * flush a bit field when it is full
 */
{
	struct decldata *q = *sptr = xalloc(sizeof(struct decldata));
	q->val.i = val;
	sptr = &(*sptr)->link;
	switch (size) {
		case 1:
			q->mode = dd_byte;
			return 1;
		case 2:
			q->mode = dd_word;
			return 2;
		case 4:
			q->mode = dd_long;
			return 4;
		default:
			q->mode = dd_byte;
			return 0;
	}
}
/* Aggregate bits */
int agbits(int size, long value)
/*
 * ombine bit declarations into a bit field
 */
{
	long rv = 0;
	if (cursize != -1 && (size != cursize || bits == -1 || (bits != -1 &&startbit==0))) {
		rv = agflush(cursize,totbits);
		cursize = -1;
		totbits = 0;
	}
	if (bits != -1) {
		totbits |= (value & bittab[bits-1]) << startbit;
		cursize = size;
	}
	else {
		if (size != -1)
			rv+= agflush(size,value);
		cursize = -1;
		totbits = 0;
	}
	startbit = -1;
	return(rv);
}
/* handle floating point init
 */
long double cppfloat(int size)
{
	TYP *t1;
	ENODE *ep;
	allocated = TRUE;
#ifdef CPLUSPLUS
	if (!prm_cplusplus)
#endif
		return floatexpr();

#ifdef CPLUSPLUS
	t1 = exprnc(&ep);
	if (isintconst(ep->nodetype))
		return ep->v.i;
	else if (isfloatconst(ep->nodetype))
		return ep->v.f;
	else {
		if (!isscalar(t1) || !ep)
			generror(ERR_NEEDCONST,0,0);
		else {
			ENODE *node1;
			int typ;
			switch (size) {
				case 6:
					typ = en_floatref;
					break;
				case 8:
					typ = en_doubleref;
					break;
				case 10:
					typ = en_longdoubleref;
					break;
			}
			node1 = makenode(typ,makenode(en_nacon,locsp,0),0);
			node1 = makenode(en_assign,node1,ep);
			cppinitinsert(node1);
		}
	}
	return 0.0;
#endif
}
/*
 * handle integer init
 */
long cppint(int size)
{
	TYP *t1;
	ENODE *ep;
	long val;
	allocated = TRUE;
#ifdef CPLUSPLUS
	if (!prm_cplusplus)
#endif
		val = intexpr(0);
#ifdef CPLUSPLUS
	else {
		t1 = exprnc(&ep);
		if (isintconst(ep->nodetype))
			val =  ep->v.i;
		else if (isfloatconst(ep->nodetype))
			val = ep->v.f;
		else {
			val = 0;
			if (!isscalar(t1) || !ep)
				generror(ERR_NEEDCONST,0,0);
			else {
		 		ENODE *node1;
			int typ;
			switch (size) {
				case -4:
					typ = en_l_ref;
					break;
				case 4:
					typ = en_ul_ref;
					break;
				case -2:
					typ = en_w_ref;
					break;
				case 2:
					typ = en_uw_ref;
					break;
				case -1:
					typ = en_b_ref;
					break;
				case 1:
					typ = en_ub_ref;
					break;
			}
				node1 = makenode(typ,makenode(en_nacon,locsp,0),0);
				node1 = makenode(en_assign,node1,ep);
				cppinitinsert(node1);
			}
		}
	}
#endif
	if (size < 0)
		size = - size;
	switch (val) {
		case 1:
			if (val < 0 || val > UCHAR_MAX)
				generror(ERR_CONSTTOOLARGE,0,0);
			break;
		case -1:
			if (val < SCHAR_MIN || val > SCHAR_MAX)
				generror(ERR_CONSTTOOLARGE,0,0);
			break;
		case 2:
			if (val < 0 || val > USHRT_MAX)
				generror(ERR_CONSTTOOLARGE,0,0);
			break;
		case -2:
			if (val < SHRT_MIN || val > SHRT_MAX)
				generror(ERR_CONSTTOOLARGE,0,0);
			break;
			/* for now ignore sizing on regular ints, may change later */
		case -4:
		case 4:
		default:
			break;
	}
	return agbits(size,val);
}
/* Basic type subroutines */
int initfloat(void)
{
	struct decldata *q = *sptr = xalloc(sizeof(struct decldata));
		q->val.f = cppfloat(6);
	sptr = &(*sptr)->link;
	q->mode = dd_float;
			return(4);
}
int initlongdouble(void)
{
	struct decldata *q = *sptr = xalloc(sizeof(struct decldata));
		q->val.f = cppfloat(10);
	sptr = &(*sptr)->link;
	q->mode = dd_ldouble;
			return(stdldoublesize);
}
int initdouble(void)
{
	struct decldata *q = *sptr = xalloc(sizeof(struct decldata));
		q->val.f = cppfloat(8);
	sptr = &(*sptr)->link;
	q->mode = dd_double;
			return(8);
}
int initchar(void)
{       
			int rv;
		rv = cppint(-1);
			return rv;
}
int initshort(void)
{   
			int rv;
		rv = cppint(-2);
			return rv;
}
int inituchar(void)
{       
			int rv;
		rv = cppint(1);
			return rv;
}
int initushort(void)
{   
			int rv;
		rv = cppint(2);
			return rv;
}
int initlong(void)
{       
			int rv;
		rv = cppint(-4);
			return rv;
}
int initulong(void)
{   
			int rv;
		rv = cppint(4);
			return rv;
}
#ifdef CPLUSPLUS
int initmemberptr(TYP *tp, SYM *btypequal)
{
	SYM *typesp;
	if (lastst == and) {
		getsym();
		if (lastst != id) {
			generror(ERR_IDEXPECT,0,0);
			basicskim(skm_declend);
		} else {
			typequal = 0;
			getsym();
			if ((typesp = gsearch(lastid)) && typesp->storage_class == sc_type) {	
				typesp = parsetype(typesp);
				if (!typesp) {
					if (typequal) {
						typesp = search(lastid,typequal->tp->lst.head);
						if (typesp)
							typesp = funcovermatch(typesp,tp);
						if (!typesp)
							genclasserror(ERR_NOFUNCMATCH,fullcppmangle(typequal,lastid,tp->btp));
						else {
							if (typesp->value.classdata.cppflags & PF_VIRTUAL) {
								SYM *sp = gen_mp_virtual_thunk(typesp);
								makeref(TRUE,sp);
							} else {
								makeref(TRUE,typesp);
							}
							typesp->tp->uflags |= UF_USED;
							getsym();
						}
		
					} else
						generror(ERR_MEMBERNAMEEXP,0,0);
        } else 
          if (typequal != btypequal || !exactype(tp,typesp->tp))
            generror(ERR_MEMBERPTRMISMATCH,0,0);
				else {
					agflush(4,typesp->value.i);
					getsym();
				}
			} else {
				generror(ERR_TYPEQUALEXP,0,0);
			  basicskim(skm_declend);
			}
		}
	} else {
		TYP *t1;
		ENODE *node,*node1;
		typequal = 0;
		t1 = exprnc(&node);
		if (t1->type != bt_memberptr || !exactype(t1->btp,tp))
			generror(ERR_MEMBERPTRMISMATCH,0,0);
		else {
			makestorage(stdmemberptrsize);
		  node1 = makenode(en_l_ref,makenode(en_nacon,locsp,0),0);
		  node1 = makenode(en_assign,node1,node);
			cppinitinsert(node1);
		}

	}
}
int initref(TYP *tp)
/*
 * init for reference variables
 */
{
	SYM *sp;
	TYP *tp1;
	ENODE *node=0,*node1;
	allocated = TRUE;
	
	tp1 = exprnc(&node);
	if (matchreflvalue(&node,locsp->tp,tp1)) {
		if (node->nodetype == en_nacon) {
			sp = gsearch(((SYM*)node->v.sp)->name);
			makeref(FALSE,sp);
		}
		else  {
			node1 = makenode(en_l_ref,makenode(en_nacon,locsp,0),0);
			node1 = makenode(en_assign,node1,node);
			cppinitinsert(node1);
			genstorage(4);
		}
	}
	endinit();
	return 4;
}
#endif
void dopointer (int makextern)
{
			SYM     *sp;
			ENODE *node=0,*node1;
			TYP *tp1;
			char *nm;
			int lst = lastst;
#ifdef CPLUSPLUS
				if (!prm_cplusplus) {
#endif
					if (lastst != and && lastst != id) {
								long temp;
								TYP *tp;
                agflush(4,temp = intexpr(&tp));
								if (temp && isscalar(tp))
									generror(ERR_NONPORT,0,0);
					}
					else {
						if (lastst == and)
							getsym();
						if (lastst != id) 
							generror(ERR_IDEXPECT,0,skm_declend);
						else {
							if( (sp = gsearch(lastid)) == 0)
				 				gensymerror(ERR_UNDEFINED,lastid);
        			else
          			getsym();
        			makeref(FALSE,sp);
							if (sp)
								sp->tp->uflags |= UF_USED;
						}
					}
#ifdef CPLUSPLUS
				}
				else {
					tp1 = exprnc(&node);
				  if (node && isintconst(node->nodetype)) {
								long temp;
								TYP *tp;
                agflush(4,temp = node->v.i);
								if (temp || (tp1->type != bt_pointer))
									generror(ERR_NONPORT,0,0);
				  }
					else if (!node || (tp1->type != bt_pointer && tp1->type != bt_func && tp1->type != bt_ifunc && !tp1->val_flag))
						gensymerror(ERR_NOINIT,locsp->name);
					else {
						if (lst != and)
							generror(ERR_PUNCT,and,skm_declend);
						else if (node->nodetype == en_nacon) {
							sp = gsearch(((SYM *)node->v.sp)->name);
							if (sp->tp->type == bt_func || sp->tp->type == bt_ifunc) {
  	            makeref(TRUE,sp);
							}
							else
      	        makeref(FALSE,sp);
							sp->tp->uflags |= UF_USED;
						}
						else  {
							if (!prm_cplusplus) 
								gensymerror(ERR_NOINIT,locsp->name);
							else {
								node1 = makenode(en_l_ref,makenode(en_nacon,locsp,0),0);
								node1 = makenode(en_assign,node1,node);
								cppinitinsert(node1);
							}
							makestorage(4);
						}
					 }
				}
#endif
}
int initpointer(void)
{       
				allocated = TRUE;
       	if(lastst == sconst) {
                makelabel();
                }
       	else if(lastst == lsconst) {
                makelabel();
                }
				else if (lastst == iconst || lastst == lconst || lastst == iuconst || lastst == luconst) {
								long temp;
								TYP *tp;
                agflush(4,temp = intexpr(&tp));
								if (temp && (tp->type != bt_pointer))
									generror(ERR_NONPORT,0,0);
				}
				else {
					dopointer(FALSE);
				}
        endinit();
        return 4;       /* pointers are 4 bytes long */
}
int initpointerfunc(void)
{       
				allocated = TRUE;
				dopointer(TRUE);
        endinit();
        return 4;       /* pointers are 4 bytes long */
}
/* Finish init */
void endinit(void)
{       if( lastst != comma && lastst != semicolon && lastst != end) {
                expecttoken(end,0);
                while( lastst != comma && lastst != semicolon && lastst != end && lastst != eof)
                        getsym();
                }
}
