示例#1
0
int parse( char *d, int i, char *c )
{
  int k, k2, k3, k4;
#ifdef CHECKALL
  if( i > numstr(d) )
    return -1;
#endif /* ifdef CHECKALL */

  k3 = -1;
  
  for(k=1; k<=i; k++) {
    k2 = wspace( d, k3+1 ); /* find start of substring */
    if( k2 == -1 )
      return -1;
    k3 = find( d, " \t", k2 ); /* find end of substring */
  }
  if( k3 == -1 ) { 
    k3 = strlen( d );
  }     
  else
    --k3; 
  
  scopy( c, d, k2, k3-k2 );
   
//  c[k4] = '\0';
 
  return 0;
}
示例#2
0
uint32 profile(const char *what, uint32 start_time)
{
    uint32 retval = MojoPlatform_ticks() - start_time;
    if (what != NULL)
        logDebug("%0 took %1 ms.", what, numstr((int) retval));
    return retval;
} // profile_start
示例#3
0
static void dumb_pager(const char *name, const char *data, size_t datalen)
{
    const int MAX_PAGE_LINES = 21;
    char *fmt = xstrdup(_("(%0-%1 of %2 lines, see more?)"));
    int i = 0;
    int w = 0;
    int linecount = 0;
    boolean getout = false;
    char **lines = splitText(data, 80, &linecount, &w);

    assert(linecount >= 0);

    printf("%s\n", name);

    if (lines == NULL)  // failed to parse?!
        printf("%s\n", data);  // just dump it all. Oh well.
    else
    {
        int printed = 0;
        do
        {
            for (i = 0; (i < MAX_PAGE_LINES) && (printed < linecount); i++)
                printf("%s", lines[printed++]);

            if (printed >= linecount)
                getout = true;
            else
            {
                char *msg = NULL;
                printf("\n");
                msg = format(fmt, numstr((printed-i)+1),
                             numstr(printed), numstr(linecount));
                getout = !MojoGui_stdio_promptyn("", msg, true);
                free(msg);
                printf("\n");
            } // else
        } while (!getout);

        for (i = 0; i < linecount; i++)
            free(lines[i]);
        free(lines);
    } // while

    free(fmt);
} // dumb_pager
示例#4
0
CString CMyButton::numstr(int n)
{
	static CString c="";
	if(n<0){
		n=n*-1;
		c="-"+numstr(n);
		return c;
	}
	if(n<10)
	{
	    c=(char)(n%10+'0');
	    return c;
	}
	else
	{
		c=numstr(n/10)+(char)(n%10+'0');
		return c;
	}
}
示例#5
0
void main()
{
  int bob, bob2, i;
  char buf[40] = "";
  
  puts( "firstnot() test" );
  bob = firstnot( "ggggXggggX", 'g', 0 );
  printf( "%d\n", bob );
  bob2 = firstnot( "ggggXggggX", 'g', bob+1 );
  printf( "%d\n", bob2 );
  bob = firstnot( "ggggXggggX", 'g', bob2+1 );
  printf( "%d\n\n", bob );
  
  puts( "neither() test" );
  bob2 = neither( "zggggXggggXz", 'g', 'X', 0 );
  printf( "%d\n", bob2 );
  bob = neither(  "zggggXggggXz", 'g', 'X', bob2+1 );
  printf( "%d\n\n", bob );
  puts( "find() test" );
  bob = find( "Dilbert and 	Dogbert", " \t", 0 );
  printf( "%d\n", bob );
  bob2 = find( "Dilbert and 	Dogbert", " \t", bob+1 );
  printf( "%d\n\n", bob2 );
  
  puts( "parse() test" );
  for(bob2=1; bob2<15; bob2++) {
    bob = parse( " The  world  is coming to an end!", bob2, buf );
    if( !bob )
      printf( "%s ", buf );
    else
      printf( "Error: %d\n\n", bob );
    /* set to nulls */
    for(i=0; i<strlen(buf); i++) {
    	buf[i] = 0;
    }
  }
  printf( "\n" ); 
  
  /* should be -1 */
  puts( "find() test part 2" );
  printf( "%d\n", find( "The happy Teletubby is  purple", " \t", 25 ) );
  
  /* should be 5 */
  puts( "numstr() test" );
  printf( "%d\n", numstr( " The happy Teletubby is  purple" ) );
   
}
示例#6
0
static void
preport(struct nwsstr *np)
{
    char *cp;
    int i;
    char buf[255];
    char num[128];
    char *ptr;

    cp = buf;
    sprintf(buf, "%-16.16s  ", ctime(&np->nws_when));
    cp += strlen(cp);
    ptr = numstr(num, np->nws_ntm);
    /*
     * vary the order of the printing of "%d times "
     */
    if (roll0(4) == 0 && np->nws_ntm > 1) {
	sprintf(cp, "%s times ", ptr);
	cp += strlen(cp);
	np->nws_ntm = 1;
    }
    strcpy(cp, cname(np->nws_ano));
    cp += strlen(cp);
    *cp++ = ' ';
    sprintf(cp, rpt[(int)np->nws_vrb].r_newstory[roll0(NUM_RPTS)],
	    cname(np->nws_vno));
    cp += strlen(cp);
    if (np->nws_ntm != 1) {
	sprintf(cp, " %s times", ptr);
	cp += strlen(cp);
    }
    if (cp - buf > 80) {
	for (i = 80; --i > 60;)
	    if (buf[i] == ' ')
		break;
	buf[i] = '\0';
	pr("%s\n\t\t  %s\n", buf, &buf[i + 1]);
    } else {
	pr("%s\n", buf);
    }
    np->nws_ntm = 0;
    return;
}
示例#7
0
static boolean MojoGui_stdio_progress(const char *type, const char *component,
                                      int percent, const char *item,
                                      boolean can_cancel)
{
    const uint32 now = ticks();

    if ( (lastComponent == NULL) ||
         (strcmp(lastComponent, component) != 0) ||
         (lastProgressType == NULL) ||
         (strcmp(lastProgressType, type) != 0) )
    {
        free(lastProgressType);
        free(lastComponent);
        lastProgressType = xstrdup(type);
        lastComponent = xstrdup(component);
        printf("%s\n%s\n", type, component);
    } // if

    // limit update spam... will only write every one second, tops,
    //  on any given filename, but it writes each filename at least once
    //  so it doesn't look like we only installed a few things.
    if (percentTicks <= now)
    {
        char *fmt = NULL;
        char *msg = NULL;
        percentTicks = now + 1000;
        if (percent < 0)
            printf("%s\n", item);
        else
        {
            fmt = xstrdup(_("%0 (total progress: %1%%)"));
            msg = format(fmt, item, numstr(percent));
            printf("%s\n", msg);
            free(msg);
            free(fmt);
        } // else
    } // if

    return true;
} // MojoGui_stdio_progress
示例#8
0
void bz_internal_error(int errcode)
{
    fatal(_("bzlib triggered an internal error: %0"), numstr(errcode));
} // bz_internal_error
示例#9
0
void c2html(const char *filename, char *err, struct colors *c)
{
	/* <- core function -> here the C source 
	   code is tranlated to an HTML web page. */

	struct /* common bits */
	{
		unsigned char color : 1;  /* color the code */
		unsigned char qt1 : 1;  /* double quotes */
		unsigned char qt2 : 1;  /* single quotes */
		unsigned char cm1 : 1;  /* multi-line comments */
		unsigned char cm2 : 1;  /* single-line comments */
		unsigned char num : 1;  /* numerical constants */
	}
	bits = { 1, 0, 0, 0, 0, 0 };

	if(!strlen(filename))
	{
		puts("\nPlease enter a filename.");
		return;
	}

	if(*filename==':')
	{
		bits.color = 0;
		filename++;
	}
	else if(*filename=='?')
	{
		userdef_colors(c);
		filename++;
	}

	FILE *cfile,*hfile;
	cfile = hfile = NULL;

	char htmlfile[STR_MAX];
	strcpy(htmlfile,filename);
	strcat(htmlfile,".html");

	if((cfile = fopen(filename,"r"))==NULL)
	{
		sprintf(err,"Could not open file: %s",filename);
		return;
	}

	printf("\nAnalyzing file: %s ...\n\n",filename);

	register char move = 0;
	unsigned int strmax, strnow, lines, pages;
	unsigned long int charcount = 0;
	strmax = strnow = lines = pages = 0;

	for(;move!=EOF;strnow++, charcount++)
	{
		move = fgetc(cfile);
		if(move=='\n')
		{
			strmax = strnow>strmax ? strnow:strmax;
			strnow = 0;
			lines++;
		}
	}

	pages = lines/50;
	pages += lines%50 < 10 ? 0 : 1;

	printf("No. of pages = %d\n",pages);
	printf("No. of lines = %d\n",lines);
	printf("No. of chars = %ld\n",charcount);
	
	if(charcount<=1)
	{
		strcpy(err,"Too few characters.");
		fclose(cfile);
		return;
	}

	if((hfile = fopen(htmlfile,"w"))==NULL)
	{
		sprintf(err,"Could not create file: %s",htmlfile);
		fclose(cfile);
		return;
	}

	printf("\nTranslating file: %s ...    ",filename);

	fprintf(hfile,"<HTML><HEAD><TITLE>%s</TITLE></HEAD>\n",filename);
	fprintf(hfile,"<BODY TEXT=%s BGCOLOR=white><CENTER><H1>%s</H1></CENTER><HR><CODE>\n",c->text,filename);

	char *wstr = NULL;
	if((wstr = (char *) malloc
	(sizeof(char)*(strmax+1)))==NULL)
	{
		strcpy(err,"Out of memory.");
		fclose(hfile);
		fclose(cfile);
		return;
	}
	else *wstr = '\0';

	unsigned int digits = 0;
	unsigned int _lines = lines;
	for(;_lines;digits++) _lines /= 10;

	char *nstr = NULL;
	if((nstr = (char *) malloc
	(sizeof(char)*(digits+1)))==NULL)
	{
		strcpy(err,"Out of memory.");
		free(wstr);
		fclose(hfile);
		fclose(cfile);
		return;
	}
	else *nstr = '\0';
	fclose(cfile);

	unsigned int lnum = 0; 
	unsigned register int cnum = 0;
	cfile = fopen(filename,"r");

	/* C keywords */
	char keys[33][9] =
	{ 
		"auto","break","case","char",
		"const","continue","default",
		"do","double","else","enum",
		"extern","float","for","goto",
		"if","int","long","register",
		"return","short","signed",
		"sizeof","static","struct",
		"switch","typedef","union",
		"unsigned","void","volatile",
		"while", "inline"
	};

	for(;fgets(wstr,strmax,cfile)!=NULL;lnum++)
	{
		/* show translation progress */
		char prog[4] = "00%";
		double progn = (lnum*100)/lines;
		if(progn<100)
		numstr(prog,(int)progn,progn<10?1:2);
		strcat(prog,"%");
		if(strlen(prog)==2)
		printf("\b\b%s",prog);
		if(strlen(prog)==3)
		printf("\b\b\b%s",prog);

		/* set some bits to zero */
		bits.qt1 = 0;
		bits.qt2 = 0;
		bits.cm2 = 0;
		bits.num = 0;

		/* insert line numbers */
		numstr(nstr,lnum,digits);
		fprintf(hfile,"<B>%s</B> &nbsp;",nstr);

		/* check if the line has been commented off */
		if(bits.cm1&&lnum)
		fprintf(hfile,"<FONT COLOR=%s>",c->comment);

		for(cnum=0;cnum<strlen(wstr);cnum++)
		{
			/* color up the keywords */
			int keyw;
			for(keyw=0;keyw<33;keyw++)
			if(!strncmp(&wstr[cnum],keys[keyw],strlen(keys[keyw]))
			   &&!(wstr[cnum-1]>'A'&&
			   wstr[cnum-1]<'Z')&&!(
			   wstr[cnum-1]>'a'&&
			   wstr[cnum-1]<'z')&&
			   wstr[cnum-1]!='_'
               &&(!bits.cm1)
               &&(!bits.cm2)
               &&(!bits.qt1)
               &&(!bits.qt2)
               &&bits.color)
			{
				fprintf(hfile,"<FONT COLOR=%s>%s</FONT>",c->keyword,keys[keyw]);
				cnum += strlen(keys[keyw]);
			}

			/* color up the comments */
			if(!strncmp(&wstr[cnum],"/*",2)
			   &&!bits.qt1
			   &&!bits.qt2
			   &&!bits.cm2
			   &&bits.color)
			{
				fprintf(hfile,"<FONT COLOR=%s>/",c->comment);
				bits.cm1 = 1;
			}
			else if(!strncmp(&wstr[cnum],"*/",2)
				    &&!bits.qt1
					&&!bits.qt2
				    &&!bits.cm2
					&&(bits.cm1)
					&&bits.color)
			{
				fprintf(hfile,"*/</FONT>");
				cnum += 2;
				bits.cm1 = 0;
			}
			else if((!strncmp(&wstr[cnum],"//",2))
				     &&!bits.qt1
					 &&!bits.qt2
				     &&!bits.cm2
					 &&!bits.cm1
					 &&bits.color)
			{
				fprintf(hfile,"<FONT COLOR=%s>/",c->comment);
				bits.cm2 = 1;
			}
			/* color up the strings */
			else if(wstr[cnum]==34
				    &&!bits.cm2
					&&!bits.cm1
					&&bits.color)
			{
				if(!bits.qt1)
				{
					fprintf(hfile,"<FONT COLOR=%s>%c",c->string,34);
					bits.qt1 = 1;
				}
				else
				{
					fprintf(hfile,"%c</FONT>",34);
					bits.qt1 = 0;
				}				
			}
			/* color up the chars */
			else if(wstr[cnum]==39
				    &&(!bits.cm2)
					&&(!bits.cm1)
					&&bits.color)
			{
				if(!bits.qt2)
				{
					fprintf(hfile,"<FONT COLOR=%s>%c",c->chr,39);
					bits.qt2 = 1;
				}
				else
				{
					fprintf(hfile,"%c</FONT>",39);
					bits.qt2 = 0;
				}				
			}
			/* color up the numbers */
			else if(wstr[cnum]>='0'&&
				    wstr[cnum]<='9'&&!(
					wstr[cnum-1]>'A'&&
					wstr[cnum-1]<'Z')&&!(
					wstr[cnum-1]>'a'&&
					wstr[cnum-1]<'z')&&
					wstr[cnum-1]!='_'
				    &&(!bits.cm2)
					&&(!bits.cm1)
					&&(!bits.qt1)
					&&(!bits.qt2)
					&&!bits.num
					&&bits.color)
			{
				fprintf(hfile,"<FONT COLOR=%s>%c",c->numbers,wstr[cnum]);
				bits.num = 1;
			}
			else if(bits.num /* to end number colouring */
				    &&((wstr[cnum]<'0')
				    ||(wstr[cnum]>'9')))
			{
			    fprintf(hfile,"</FONT>%c",wstr[cnum]);
				bits.num = 0;
			}

			/* replace the C symbols
			 with their HTML equivalent */
			else if(wstr[cnum-1]==' '&&wstr[cnum]==' ')
			fprintf(hfile,"&nbsp;");
			else if(wstr[cnum]=='\t')
			fprintf(hfile,"&nbsp; ");
			else if(wstr[cnum]=='<')
			fprintf(hfile,"&lt;");
			else if(wstr[cnum]=='>')
			fprintf(hfile,"&gt;");
			else if(wstr[cnum]=='\n')
			break;
			else
			fprintf(hfile,"%c",wstr[cnum]);
		}
		/* end font tag */
		if(bits.cm1||
		   bits.cm2||
		   bits.qt1||
		   bits.qt2||
		   bits.num)
		fprintf(hfile,"</FONT>");
		/* end the line */
		fprintf(hfile,"<BR>\n");
	}

	fputs("</CODE><HR NOSHADE><FONT FACE=Arial>\n",hfile);
	fprintf(hfile,"No. of pages = %d<BR>\n",pages);
	fprintf(hfile,"No. of lines = %d<BR>\n",lines);
	fprintf(hfile,"No. of chars = %ld<BR>\n",charcount);
	fputs("</FONT></BODY></HTML>",hfile);
	puts("\b\b\b100%\n\nTranslation Complete.");
	printf("HTML File: %s stored.\n",htmlfile);
	free(wstr);
	fclose(hfile);
	fclose(cfile);
}
示例#10
0
void c2html(const char *filename, char *err)
{
	/* In this function the source code
	 * is tranlate to an HTML web page.
	 */

	if(!strlen(filename))
	{
		puts("\nPlease enter a filename.");
		return;
	}

	FILE *cfile,*hfile;
	cfile = hfile = NULL;

	char htmlfile[STR_MAX];
	strcpy(htmlfile,filename);
	strcat(htmlfile,".html");

	if((cfile = fopen(filename,"r"))==NULL)
	{
		sprintf(err,"Could not open file: %s",filename);
		return;
	}

	printf("\nAnalyzing file: %s ...\n\n",filename);

	register char move = 0;
	unsigned int strmax, strnow, lines, pages;
	unsigned long int charcount = 0;
	strmax = strnow = lines = pages = 0;

	for(;move!=EOF;strnow++, charcount++)
	{
		move = fgetc(cfile);
		if(move=='\n')
		{
			strmax = strnow>strmax ? strnow:strmax;
			strnow = 0;
			lines++;
		}
	}

	pages = lines/50;
	pages += lines%50 < 10 ? 0 : 1;

	printf("No. of pages = %d\n",pages);
	printf("No. of lines = %d\n",lines);
	printf("No. of chars = %ld\n",charcount);
	
	printf("\nTranslating file: %s ...\n",filename);

	if(charcount<=1)
	{
		strcpy(err,"Too few characters.");
		fclose(cfile);
		return;
	}

	if((hfile = fopen(htmlfile,"w"))==NULL)
	{
		sprintf(err,"Could not create file: %s",htmlfile);
		fclose(cfile);
		return;
	}

	fprintf(hfile,"<HTML><HEAD><TITLE>%s</TITLE></HEAD>\n",filename);
	fprintf(hfile,"<BODY><CENTER><H1>%s</H1></CENTER><HR><CODE>\n",filename);

	char *wstr = NULL;
	if((wstr = (char *) malloc
	(sizeof(char)*(strmax+1)))==NULL)
	{
		strcpy(err,"Out of memory.");
		fclose(hfile);
		fclose(cfile);
		return;
	}
	else *wstr = '\0';

	unsigned int digits = 0;
	unsigned int _lines = lines;
	for(;_lines;digits++) _lines /= 10;

	char *nstr = NULL;
	if((nstr = (char *) malloc
	(sizeof(char)*(digits+1)))==NULL)
	{
		strcpy(err,"Out of memory.");
		fclose(hfile);
		fclose(cfile);
		return;
	}
	else *nstr = '\0';
	fclose(cfile);

	unsigned int lnum = 0, cnum = 0;
	cfile = fopen(filename,"r");

	for(;fgets(wstr,strmax,cfile)!=NULL;lnum++)
	{
		numstr(nstr,lnum,digits);
		fprintf(hfile,"<B> %s </B> &nbsp;",nstr);
		for(cnum=0;cnum<strlen(wstr);cnum++)
		{
			if(wstr[cnum]=='\n')
			fprintf(hfile,"<BR>\n");
			else if(wstr[cnum]=='\t')
			fprintf(hfile," &nbsp; ");
			else if(wstr[cnum]=='<')
			fprintf(hfile,"&lt;");
			else if(wstr[cnum]=='>')
			fprintf(hfile,"&gt;");
			else
			fprintf(hfile,"%c",wstr[cnum]);
		}
	}

	fputs("</CODE><HR NOSHADE><FONT FACE=Arial>\n",hfile);
	fprintf(hfile,"No. of pages = %d<BR>\n",pages);
	fprintf(hfile,"No. of lines = %d<BR>\n",lines);
	fprintf(hfile,"No. of chars = %ld<BR>\n",charcount);
	fputs("</FONT></BODY></HTML>",hfile);
	puts("\nTranslation Complete.");
	printf("HTML File: %s stored.\n",htmlfile);
	free(wstr);
	fclose(hfile);
	fclose(cfile);
}
示例#11
0
int
news(void)
{
    struct natstr *natp;
    time_t now;
    int page;
    time_t then;
    time_t delta;
    struct nwsstr nws;
    struct nstr_item nstr;
    int page_has_news[N_MAX_PAGE + 1];
    int there_is_news = 0;
    short sectors_taken[MAXNOC][MAXNOC];
    short sectors_delta;
    short max_delta = -1;
    short abs_delta;
    short k;
    int sectors_were_taken = 0;
    natid i, j;
    char num[128];
    char *verb;

    if (!snxtitem(&nstr, EF_NEWS, "*", NULL))
	return RET_SYN;
    memset(page_has_news, 0, sizeof(page_has_news));
    memset(sectors_taken, 0, sizeof(sectors_taken));
    (void)time(&now);
    natp = getnatp(player->cnum);
    then = natp->nat_newstim;
    if (player->argp[1]) {
	/*
	 * We want to hide events before contact.  Proper solution
	 * would be to timestamp the contact.  Cheesy approximation:
	 * disable old news.
	 */
	if (opt_HIDDEN && !player->god) {
	    pr("Sorry, argument doesn't work with HIDDEN enabled\n");
	    return RET_FAIL;
	}
	delta = days(atoi(player->argp[1]));
	then = now - delta;
    }
    natp->nat_newstim = now;
    head();
    pr("\nThe details of Empire news since %s", ctime(&then));
    while (nxtitem(&nstr, &nws)) {
	if (!nws.nws_vrb || CANT_HAPPEN(nws.nws_vrb > N_MAX_VERB))
	    continue;
	if (nws.nws_when < then)
	    continue;
	if (opt_HIDDEN) {
	    if (!player->god &&
		!(getcontact(getnatp(player->cnum), nws.nws_ano) &&
		  getcontact(getnatp(player->cnum), nws.nws_vno)))
		continue;
	}
	++page_has_news[rpt[(int)nws.nws_vrb].r_newspage];
	++there_is_news;
    }
    for (page = 1; page <= N_MAX_PAGE; page++) {
	if (!page_has_news[page])
	    continue;
	pr("\n\t ===  %s  ===\n", page_headings[page].name);
	snxtitem_rewind(&nstr);
	while (nxtitem(&nstr, &nws)) {
	    if (CANT_HAPPEN(nws.nws_vrb > N_MAX_VERB))
		continue;
	    if (rpt[(int)nws.nws_vrb].r_newspage != page)
		continue;
	    if (nws.nws_when < then)
		continue;
	    if (nws.nws_ntm == 0)
		nws.nws_ntm = 1;
	    if (opt_HIDDEN) {
		if (!player->god &&
		    !(getcontact(getnatp(player->cnum), nws.nws_ano) &&
		      getcontact(getnatp(player->cnum), nws.nws_vno)))
		    continue;
	    }
	    if (page == N_FRONT &&
		(nws.nws_vrb == N_WON_SECT ||
		 nws.nws_vrb == N_AWON_SECT ||
		 nws.nws_vrb == N_PWON_SECT)) {
		sectors_taken[nws.nws_ano][nws.nws_vno] += nws.nws_ntm;
		sectors_were_taken += nws.nws_ntm;
	    }
	    preport(&nws);
	}
    }
    if (sectors_were_taken) {
	for (i = 0; i < MAXNOC; ++i) {
	    for (j = 0; j < i; ++j) {
		sectors_delta = sectors_taken[i][j] - sectors_taken[j][i];
		if (max_delta < abs(sectors_delta))
		    max_delta = abs(sectors_delta);
	    }
	}
	pr("\n\t ===  The Bottom Line   ==\n");
	for (k = max_delta; k > 0; --k) {
	    for (i = 0; i < MAXNOC; ++i) {
		for (j = 0; j < i; ++j) {
		    sectors_delta = sectors_taken[i][j] -
			sectors_taken[j][i];
		    abs_delta = abs(sectors_delta);
		    if (abs_delta != k)
			continue;
		    if (abs_delta == 1)
			verb = "stole";
		    else if (abs_delta < 4)
			verb = "took";
		    else if (abs_delta < 8)
			verb = "captured";
		    else
			verb = "seized";
		    if (sectors_delta > 0) {
			numstr(num, abs_delta);
			pr("%s %s %s sector%s from %s\n", cname(i), verb,
			   num, splur(sectors_delta), cname(j));
		    } else if (sectors_delta < 0) {
			numstr(num, abs_delta);
			pr("%s %s %s sector%s from %s\n", cname(j), verb,
			   num, splur(-sectors_delta), cname(i));
		    }
		}
	    }
	}
    }
    if (!there_is_news)
	pr("\nNo news at the moment...\n");
    return 0;
}
示例#12
0
EXPORT int  mongo_bson_buffer_append(struct bson_buffer* b, char* name, mxArray* value) {
    size_t numel = mxGetNumberOfElements(value);
    mxClassID cls = mxGetClassID(value);
    bson* _b = (bson*)b;
    mwSize i, j;
    mwSize dims[MAXDIM];
    mwSize ijk[MAXDIM];
    mwSize sizes[MAXDIM];
    mwSize ndims;
    const mwSize *odims;
    int depth = 0;
    int success;
    if (numel == 1) {
        /* Append a single element using the given name */
        switch (cls) {
        case mxLOGICAL_CLASS:
            return (bson_append_bool(_b, name, ((char*)mxGetData(value))[0]) == BSON_OK);
        case mxDOUBLE_CLASS:
            if (mxIsComplex(value))
                return mongo_bson_buffer_append_complex(b, name, mxGetPr(value)[0], mxGetPi(value)[0]);
            else
                return (bson_append_double(_b, name, mxGetPr(value)[0]) == BSON_OK);
        case mxSINGLE_CLASS:
            return (bson_append_double(_b, name, ((float*)mxGetData(value))[0]) == BSON_OK);
        case mxINT8_CLASS:
            return (bson_append_int(_b, name, ((signed char*)mxGetData(value))[0]) == BSON_OK);
        case mxUINT8_CLASS:
            return (bson_append_int(_b, name, ((unsigned char*)mxGetData(value))[0]) == BSON_OK);
        case mxINT16_CLASS:
            return (bson_append_int(_b, name, ((short*)mxGetData(value))[0]) == BSON_OK);
        case mxUINT16_CLASS:
            return (bson_append_int(_b, name, ((unsigned short*)mxGetData(value))[0]) == BSON_OK);
        case mxINT32_CLASS:
            return (bson_append_int(_b, name, ((int*)mxGetData(value))[0]) == BSON_OK);
        case mxUINT32_CLASS:
            return (bson_append_int(_b, name, ((unsigned int*)mxGetData(value))[0]) == BSON_OK);
        case mxINT64_CLASS: ;
        case mxUINT64_CLASS:
            return (bson_append_long(_b, name, ((int64_t*)mxGetData(value))[0]) == BSON_OK);
        default:
            mexPrintf("BsonBuffer:append - Unhandled type: %s\n", mxGetClassName(value));
            return 0;
        }
    }
    success = (bson_append_start_array(_b, name) == BSON_OK);
    odims = mxGetDimensions(value);
    ndims = mxGetNumberOfDimensions(value);
    memcpy(dims, odims, ndims*sizeof(mwSize));
    if (ndims > 1)
        reverse(dims, ndims);
    i = ndims;
    /* calculate offset to multiply each dimension's index by */
    j = 1;
    do {
        i--;
        sizes[i] = j;
        j *= dims[i];
    } while (i > 0);
    if (ndims == 2 && dims[1] == 1)
        ndims--;  /* 1 dimensional row vector */
    if (ndims > 1) {
        /* reverse row and columns */
        j = dims[ndims-1];
        dims[ndims-1] = dims[ndims-2];
        dims[ndims-2] = j;
        j = sizes[ndims-1];
        sizes[ndims-1] = sizes[ndims-2];
        sizes[ndims-2] = j;
    }
    memset(ijk, 0, ndims * sizeof(mwSize));
    while (success && depth >= 0) {
        if (ijk[depth] < dims[depth]) {
            const char* num = numstr((int)(ijk[depth]++));
            if (depth < (int)(ndims - 1)) {
                depth++;
                success = (bson_append_start_array(_b, num) == BSON_OK);
            }
            else {
                i = 0;
                for (j = 0; j < ndims; j++)
                    i += (ijk[j]-1) * sizes[j];
                switch (cls) {
                case mxLOGICAL_CLASS:
                    success = (bson_append_bool(_b, num, ((char*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxDOUBLE_CLASS:
                    if (mxIsComplex(value))
                        success = mongo_bson_buffer_append_complex(b, num, mxGetPr(value)[i], mxGetPi(value)[i]);
                    else
                        success = (bson_append_double(_b, num, mxGetPr(value)[i]) == BSON_OK);
                    break;
                case mxSINGLE_CLASS:
                    success = (bson_append_double(_b, num, ((float*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxINT8_CLASS:
                    success = (bson_append_int(_b, num, ((signed char*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxUINT8_CLASS:
                    success = (bson_append_int(_b, num, ((unsigned char*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxINT16_CLASS:
                    success = (bson_append_int(_b, num, ((short*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxUINT16_CLASS:
                    success = (bson_append_int(_b, num, ((unsigned short*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxINT32_CLASS:
                    success = (bson_append_int(_b, num, ((int*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxUINT32_CLASS:
                    success = (bson_append_int(_b, num, ((unsigned int*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxINT64_CLASS: ;
                case mxUINT64_CLASS:
                    success = (bson_append_long(_b, num, ((int64_t*)mxGetData(value))[i]) == BSON_OK);
                    break;
                default:
                    mexPrintf("BsonBuffer:append - Unhandled type: %s\n", mxGetClassName(value));
                    return 0;
                }
            }
        }
        else {
            ijk[depth] = 0;
            success = (bson_append_finish_object(_b) == BSON_OK);
            depth--;
        }
    }
    return success;
}
示例#13
0
EXPORT int  mongo_bson_buffer_append_date(struct bson_buffer* b, char *name, mxArray* value) {
    size_t numel = mxGetNumberOfElements(value);
    mxClassID cls = mxGetClassID(value);
    bson* _b = (bson*)b;
    mwSize i, j;
    mwSize dims[MAXDIM];
    mwSize ijk[MAXDIM];
    mwSize sizes[MAXDIM];
    mwSize ndims;
    const mwSize *odims; /* original dimensions */
    char* p;
    int depth = 0;
    int success;
    if (cls != mxDOUBLE_CLASS) {
        mexPrintf("Only double values are permitted in appendDate\n");
        return 0;
    }
    if (numel == 1)
        return (bson_append_date(_b, name, (bson_date_t)((mxGetPr(value)[0] - 719529) * (1000 * 60 * 60 * 24)) ) == BSON_OK);
    success = (bson_append_start_array(_b, name) == BSON_OK);
    odims = mxGetDimensions(value);
    ndims = mxGetNumberOfDimensions(value);
    memcpy(dims, odims, ndims*sizeof(mwSize));
    if (ndims > 1)
        reverse(dims, ndims);
    i = ndims;
    j = 1;
    /* calculate offset to multiply each dimension's index by */
    do {
        i--;
        sizes[i] = j;
        j *= dims[i];
    } while (i > 0);
    if (ndims == 2 && dims[1] == 1)
        ndims--;
    if (ndims > 1) {
        /* reverse row and columns */
        j = dims[ndims-1];
        dims[ndims-1] = dims[ndims-2];
        dims[ndims-2] = j;
        j = sizes[ndims-1];
        sizes[ndims-1] = sizes[ndims-2];
        sizes[ndims-2] = j;
    }
    memset(ijk, 0, ndims * sizeof(mwSize));
    p = (char*)mxGetData(value);
    while (success && depth >= 0) {
        if (ijk[depth] < dims[depth]) {
            const char* num = numstr((int)(ijk[depth]++));
            if (depth < (int)(ndims - 1)) {
                depth++;
                success = (bson_append_start_array(_b, num) == BSON_OK);
            }
            else {
                i = 0;
                for (j = 0; j < ndims; j++)
                    i += (ijk[j]-1) * sizes[j];
                success = (bson_append_date(_b, num, (bson_date_t)((mxGetPr(value)[i] - 719529) * (1000 * 60 * 60 * 24)) ) == BSON_OK);
            }
        }
        else {
            ijk[depth] = 0;
            success = (bson_append_finish_object(_b) == BSON_OK);
            depth--;
        }
    }
    return success;
}
示例#14
0
文件: main.cpp 项目: scrpi/zasm
/* ---- program entry ---------------------------
*/
int main( int argc, cstr argv[] )
{
	double start = now();

// options:
	uint verbose     = 1;	// 0=off, 1=default, 2=verbose
	uint outputstyle = 'b';	// 0=none, 'b'=binary, 'x'=intel hex, 's'=motorola s-records
	uint liststyle   = 1;	// 0=none, 1=plain, 2=with objcode, 4=with label listing, 6=both, 8=clock cycles
	bool clean		 = no;
	bool ixcbr2		 = no;
	bool ixcbxh		 = no;
	bool targetZ80	 = no;
	bool target8080	 = no;
	bool targetZ180  = no;
	bool asm8080	 = no;
	bool dotnames    = no;
	bool reqcolon    = no;
	bool casefold    = no;
	bool flatops	 = no;
	bool compare     = no;
	bool selftest    = no;
	bool cgi_mode	 = no;
	uint maxerrors   = 30;
// filepaths:
	cstr inputfile  = NULL;
	cstr outputfile = NULL;	// or dir
	cstr listfile   = NULL;	// or dir
	cstr tempdir    = NULL;
	cstr c_compiler = NULL;
	cstr c_includes	= NULL;
	cstr libraries	= NULL;

//	eval arguments:
	for(int i=1; i<argc; )
	{
		cptr s = argv[i++];

		if(s[0] != '-')
		{
			if(!inputfile)  { inputfile = s; continue; }
			// if outfile is not prefixed with -o then it must be the last argument:
			if(!outputfile && i==argc) { outputfile = s; continue; }
			if(!listfile)   { listfile = s; continue; }
			goto h;
		}

		if(s[1]=='-')
		{
			if(eq(s,"--clean"))    { clean = yes;     continue; }
			if(eq(s,"--bin"))	   { outputstyle='b'; continue; }
			if(eq(s,"--hex"))	   { outputstyle='x'; continue; }
			if(eq(s,"--s19"))	   { outputstyle='s'; continue; }
			if(eq(s,"--opcodes"))  { liststyle |= 2;  continue; }
			if(eq(s,"--labels"))   { liststyle |= 4;  continue; }
			if(eq(s,"--cycles"))   { liststyle |= 8;  continue; }
			if(eq(s,"--ixcbr2"))   { ixcbr2 = 1;      continue; }
			if(eq(s,"--ixcbxh"))   { ixcbxh = 1;      continue; }
			if(eq(s,"--z80"))      { targetZ80 = 1;   continue; }
			if(eq(s,"--8080"))     { target8080 = 1;  continue; }
			if(eq(s,"--asm8080"))  { asm8080 = 1;     continue; }
			if(eq(s,"--z180"))     { targetZ180 = 1;  continue; }
			if(eq(s,"--dotnames")) { dotnames = 1;    continue; }
			if(eq(s,"--reqcolon")) { reqcolon = 1;    continue; }
			if(eq(s,"--casefold")) { casefold = 1;    continue; }
			if(eq(s,"--flatops"))  { flatops = 1;     continue; }
			if(eq(s,"--compare"))  { compare = 1;     continue; }
			if(eq(s,"--test"))     { selftest = 1;    continue; }
			if(eq(s,"--cgi"))      { cgi_mode = 1;    continue; }
			if(startswith(s,"--maxerrors="))
				{
					char* ep; ulong n = strtoul(s+12,&ep,10);
					if(*ep||n==0||n>999) goto h;
					maxerrors = (uint)n; continue;
				}
			goto h;
		}

		while(char c = *++s)
		{
			switch(c)
			{
			case 'e': compare = 1; continue;
			case 'T': selftest = 1; continue;
			case 'u': liststyle |= 2; continue;
			case 'w': liststyle |= 4; continue;
			case 'y': liststyle |= 8; continue;
			case 's': outputstyle=c; continue;
			case 'x': outputstyle=c; continue;
			case 'b': outputstyle=c; continue;
			case 'z': clean=yes; continue;
			case 'g': cgi_mode=yes; continue;

			case 'v': if(*(s+1)>='0' && *(s+1)<='3') verbose = *++s - '0'; else ++verbose; continue;

			case 'i': if(inputfile  || i==argc) goto h; else inputfile  = argv[i++]; continue;
			case 'o': if(*(s+1)=='0') { outputstyle = 0; ++s; continue; }
					  if(outputfile || i==argc) goto h; else outputfile = argv[i++]; continue;
			case 'l': if(*(s+1)=='0') { liststyle = 0; ++s; continue; }
					  if(listfile   || i==argc) goto h; else listfile   = argv[i++]; continue;

			case 'I': if(c_includes || i==argc) goto h; else c_includes = argv[i++]; continue;
			case 'L': if(libraries|| i==argc) goto h; else libraries= argv[i++]; continue;
			case 'c': if(c_compiler || i==argc) goto h; else c_compiler = argv[i++]; continue;
			case 't': if(tempdir    || i==argc) goto h; else tempdir    = argv[i++]; continue;
			default:  goto h;
			}
		}
	}

	if(selftest)
	{
		// assemble a bunch of sources from the $PROJECT/Test/ directory
		// and compare them to old versions found in the original/ subdirectories.

		// if no path to the $PROJECT directory is given, then the current working directory is used.
		// all expected sources and original output files must be in place and match.
		cstr zasm = argv[0];
		cstr testdir = fullpath( inputfile ? inputfile : outputfile ? outputfile : "./" );
		if(errno==ok && lastchar(testdir)!='/') errno = ENOTDIR;
		if(errno)
		{
			if(verbose) fprintf(stderr, "--> %s: %s\nzasm: 1 error\n", testdir, strerror(errno));
			return 1;
		}

		// if compiler was given, then it will be checked by the recursively called main()
		// else: no c compiler given: try to use scdd from $PROJECT/sdcc/bin/
		if(!c_compiler)
        {
			#ifdef _BSD
				c_compiler = catstr(testdir,"sdcc/bin/sdcc");
			#endif
			#ifdef _LINUX
				c_compiler = catstr(testdir,"sdcc/bin-Linux32/sdcc");
			#endif
			if(!is_file(c_compiler) || !is_executable(c_compiler))
				c_compiler = NULL;		// passing "-c" + NULL should not crash main()
		}

		uint errors = 0;
		char opt[] = "-v0e"; opt[2] += verbose;

		change_working_dir(catstr(testdir,"Test/ZXSP/"));
		{
			cstr a[] = { zasm, opt, "template_o.asm", "original/" };
			errors += main(NELEM(a),a);

			a[2] = "template_p.asm";
			errors += main(NELEM(a),a);

			a[2] = "template_ace.asm";
			errors += main(NELEM(a),a);

			a[2] = "template_tap.asm";
			errors += main(NELEM(a),a);

			a[2] = "template_z80.asm";
			errors += main(NELEM(a),a);

			a[2] = "template_sna.asm";
			errors += main(NELEM(a),a);

			a[2] = "mouse.asm";
			errors += main(NELEM(a),a);

			cstr b[] = { zasm, opt, "-c", c_compiler, "template_rom_with_c_code.asm", "original/" };
			errors += main(NELEM(b),b);
		}

		change_working_dir(catstr(testdir,"Test/Z80/"));
		{
			cstr a[] = { zasm, opt, "ZX Spectrum Rom/zx82.asm", "original/" };
			errors += main(NELEM(a),a);

			cstr c[] = { zasm,  opt, "--casefold", "CAMEL80-12/camel80.asm", "original/" };
			errors += main(NELEM(c),c);

			cstr d[] = { zasm, opt, "monitor_32k.asm", "original/" };
			errors += main(NELEM(d),d);

			cstr e[] = { zasm, opt, "allsrc.asm", "original/" };
			errors += main(NELEM(e),e);

			cstr f[] = { zasm, opt, "basic.asm", "original/" };
			errors += main(NELEM(f),f);

			cstr g[] = { zasm, opt, "MS-Basic.asm", "original/" };
			errors += main(NELEM(g),g);

			cstr h[] = { zasm, opt, "--reqcolon", "5bsort018.asm", "original/" };
			errors += main(NELEM(h),h);

			cstr i[] = { zasm, opt, "64#4+016.asm", "original/" };
			errors += main(NELEM(i),i);

			cstr j[] = { zasm, opt, "--8080", "CPM22.asm", "original/" };
			errors += main(NELEM(j),j);

			cstr k[] = { zasm, opt, "EMUF/EMUF.asm", "original/" };
			errors += main(NELEM(k),k);

			cstr l[] = { zasm, opt, "G007_MON_source_recreation.asm", "original/" };
			errors += main(NELEM(l),l);

			cstr n[] = { zasm, opt, "--reqcolon", "Hello World.asm", "original/" };
			errors += main(NELEM(n),n);

			cstr o[] = { zasm, opt, "--8080", "m80b.asm", "original/" };
			errors += main(NELEM(o),o);

			cstr p[] = { zasm, opt, "monitor_32k.asm", "original/" };
			errors += main(NELEM(p),p);

			cstr q[] = { zasm, opt, "MS-Basic.asm", "original/" };
			errors += main(NELEM(q),q);

			cstr r[] = { zasm, opt, "mybios4_mod.asm", "original/" };
			errors += main(NELEM(r),r);

			cstr s[] = { zasm, opt, "--dotnames", "--reqcolon", "OpenSE Basic/opense.asm", "original/" };
			errors += main(NELEM(s),s);

			cstr b[] = { zasm, opt, "ZX Spectrum Rom/sc178.asm", "original/" };
			errors += main(NELEM(b),b);

			cstr m[] = { zasm, opt, "test z80 cpu - prelim.asm", "original/" };
			errors += main(NELEM(m),m);

			cstr t[] = { zasm, opt, "--reqcolon", "VZ200 RS232 Terminal/VZ RS232.asm", "original/" };
			errors += main(NELEM(t),t);

			cstr u[] = { zasm, opt, "wmfw/wmfw2_5_orig.asm", "original/" };
			errors += main(NELEM(u),u);

			cstr v[] = { zasm, opt, "z80mon.asm", "original/" };
			errors += main(NELEM(v),v);

			cstr w[] = { zasm, opt, "z80sourc.asm", "original/" };
			errors += main(NELEM(w),w);

			cstr x[] = { zasm, opt, "--reqcolon", "zx81v2.asm", "original/" };
			errors += main(NELEM(x),x);

			cstr y[] = { zasm, opt, "--ixcbr2", "zasm-test-opcodes.asm", "original/" };
			errors += main(NELEM(y),y);
		}

		change_working_dir(catstr(testdir,"Test/8080/"));
		{
			cstr a[] = { zasm, opt, "--asm8080", "--reqcolon", "Altair8800_Monitor.asm", "original/" };
			errors += main(NELEM(a),a);

			cstr b[] = { zasm, opt, "8080PRE.asm", "original/" };
			errors += main(NELEM(b),b);

			cstr y[] = { zasm, opt, "zasm-test-opcodes.asm", "original/" };
			errors += main(NELEM(y),y);
		}

		change_working_dir(catstr(testdir,"Test/Z180/"));
		{
			cstr a[] = { zasm, opt, "--z180", "first.asm", "original/" };
			errors += main(NELEM(a),a);

			cstr b[] = { zasm, opt, "--z180", "counter master.asm", "original/" };
			errors += main(NELEM(b),b);

			cstr y[] = { zasm, opt, "zasm-test-opcodes.asm", "original/" };
			errors += main(NELEM(y),y);
		}

		if(verbose)
		{
			fprintf(stderr, "\ntotal time: %3.4f sec.\n", now()-start);
			if(errors>1) fprintf(stderr, "\nzasm: %u errors\n\n", errors);
			else fprintf(stderr, errors ? "\nzasm: 1 error\n\n" : "zasm: no errors\n");
		}
		return errors>0;
	}

// check options:
	if(targetZ180)			  targetZ80  = yes;		// implied
	if(asm8080 && !targetZ80) target8080 = yes;		// only implied   if not --Z80 set
	if(!target8080)			  targetZ80  = yes;		// default to Z80 if not --8080 or --asm8080 set

	if(asm8080 && targetZ180)
	{
		fprintf(stderr,"--> %s\nzasm: 1 error\n", "the 8080 assembler does not support Z180 opcodes.");
		return 1;
	}

	if(target8080 && targetZ80)
	{
		fprintf(stderr,"--> %s\nzasm: 1 error\n", "--8080 and --z80|--z180 are mutually exclusive.");
		return 1;
	}

	if(ixcbr2 || ixcbxh)
	{
		if(target8080)
		{
			fprintf(stderr,"--> %s\nzasm: 1 error\n", "i8080 has no index registers and no prefix 0xCB instructions.");
			return 1;
		}

		if(targetZ180)
		{
			fprintf(stderr,"--> %s\nzasm: 1 error\n", "no --ixcb… allowed: the Z180 traps illegal instructions");
			return 1;
		}

		if(asm8080)
		{
			fprintf(stderr,"--> %s\nzasm: 1 error\n", "the 8080 assembler does not support illegal opcodes.");
			return 1;
		}

		if(ixcbr2 && ixcbxh)
		{
			fprintf(stderr,"--> %s\nzasm: 1 error\n", "--ixcbr2 and --ixcbxh are mutually exclusive.");
			return 1;
		}
	}


// check source file:
	if(!inputfile)
	{
		h: fprintf(stderr, help, version, compiledatestr(), _PLATFORM);
		return 1;
	}
	inputfile = fullpath(inputfile,no);
	if(errno)
	{
		if(verbose) fprintf(stderr, "--> %s: %s\nzasm: 1 error\n", inputfile, strerror(errno));
		return 1;
	}
	if(!is_file(inputfile))
	{
		if(verbose) fprintf(stderr, "--> %s: not a regular file\nzasm: 1 error\n", inputfile);
		return 1;
	}

// check output file or dir:
	if(!outputfile) outputfile = directory_from_path(inputfile);
	outputfile = fullpath(outputfile);
	if(errno && errno!=ENOENT)
	{
		if(verbose) fprintf(stderr, "--> %s: %s\nzasm: 1 error\n", outputfile, strerror(errno));
		return 1;
	}

// check list file or dir:
	if(!listfile) listfile = directory_from_path(outputfile);
	listfile = fullpath(listfile);
	if(errno && errno!=ENOENT)
	{
		if(verbose) fprintf(stderr, "--> %s: %s\nzasm: 1 error\n", listfile, strerror(errno));
		return 1;
	}

// check temp dir:
	if(!tempdir) tempdir = directory_from_path(outputfile);
	tempdir = fullpath(tempdir);
	if(errno && errno!=ENOENT)
	{
		if(verbose) fprintf(stderr, "--> %s: %s\nzasm: 1 error\n", tempdir, strerror(errno));
		return 1;
	}
	if(lastchar(tempdir)!='/')
	{
		if(verbose) fprintf(stderr, "--> %s: %s\nzasm: 1 error\n", tempdir, strerror(ENOTDIR));
		return 1;
	}

// check c_includes path:
	if(c_includes)
	{
		c_includes = fullpath(c_includes);
		if(errno==ok && lastchar(c_includes)!='/') errno = ENOTDIR;
		if(errno)
		{
			if(verbose) fprintf(stderr, "--> %s: %s\nzasm: 1 error\n", c_includes, strerror(errno));
			return 1;
		}
	}

// check c_libraries path:
	if(libraries)
	{
		libraries = fullpath(libraries);
		if(errno==ok && lastchar(libraries)!='/') errno = ENOTDIR;
		if(errno)
		{
			if(verbose) fprintf(stderr, "--> %s: %s\nzasm: 1 error\n", libraries, strerror(errno));
			return 1;
		}
	}

// check cc_path:
	if(c_compiler)
	{
		if(c_compiler[0]!='/')
		{
			cstr s = quick_fullpath(c_compiler);
			if(is_file(s))
				c_compiler = s;
			else
			{
				Array<str> ss;
				split(ss, getenv("PATH"), ':');
				for(uint i=0; i<ss.count(); i++)
				{
					s = catstr(ss[i],"/",c_compiler);
					if(is_file(s)) { c_compiler = s; break; }
				}
			}
		}

		c_compiler = fullpath(c_compiler);
		if(errno)
		{
			if(verbose) fprintf(stderr, "--> %s: %s\nzasm: 1 error\n", c_compiler, strerror(errno));
			return 1;
		}
		if(!is_file(c_compiler))
		{
			if(verbose) fprintf(stderr, "--> %s: not a regular file\nzasm: 1 error\n", c_compiler);
			return 1;
		}
		if(!is_executable(c_compiler))
		{
			if(verbose) fprintf(stderr, "--> %s: not executable\nzasm: 1 error\n", c_compiler);
			return 1;
		}
	}

// DO IT!
	Z80Assembler ass;
	ass.verbose = verbose;
	ass.ixcbr2_enabled = ixcbr2;
	ass.ixcbxh_enabled = ixcbxh;
	ass.target_8080    = target8080;
	ass.target_z80     = targetZ80;
	ass.target_z180    = targetZ180;
	ass.asm8080    = asm8080;
	ass.require_colon  = reqcolon;
	ass.allow_dotnames = dotnames;
	ass.casefold= casefold;
	ass.flat_operators = flatops;
	ass.max_errors     = maxerrors;
	ass.compare_to_old = compare;
	ass.cgi_mode	   = cgi_mode;
	if(c_includes) ass.c_includes = c_includes;
	if(libraries) ass.stdlib_dir  = libraries;
	if(c_compiler) ass.c_compiler = c_compiler;
	ass.assembleFile( inputfile, outputfile, listfile, tempdir, liststyle, outputstyle, clean );

	uint errors = ass.errors.count();

	if(verbose)		// show errors on stderr:
	{
		cstr current_file = NULL;
		for(uint i=0; i<errors; i++)
		{
			Error const& e = ass.errors[i];
			SourceLine* sourceline = e.sourceline;
			if(!sourceline)
			{
				if(current_file) fprintf(stderr,"\n"); current_file=NULL; fprintf(stderr,"--> %s\n",e.text);
				continue;
			}

			cstr filename = sourceline->sourcefile;
			if(filename!=current_file)				// note: compare pointers!
			{
				current_file = filename;
				fprintf(stderr, "\nin file %s:\n", filename_from_path(filename));
			}

			cstr linenumber = numstr(sourceline->sourcelinenumber+1);
			fprintf(stderr, "%s: %s\n", linenumber, sourceline->text);
			fprintf(stderr, "%s%s^ %s\n", spacestr(strlen(linenumber)+2), sourceline->whitestr(), e.text);
		}

		fprintf(stderr, "assemble: %u lines\n", ass.source.count());
		fprintf(stderr, "time: %3.4f sec.\n", now()-start);
		if(errors>1) fprintf(stderr, "\nzasm: %u errors\n\n", errors);
		else fprintf(stderr, errors ? "\nzasm: 1 error\n\n" : "zasm: no errors\n");
	}

	return errors>0;	// 0=ok, 1=errors
}
示例#15
0
  /**
   * Build the geom list as part of cell construction.
   * Each item in the list will be a string; either " ", ":", or "#", indicating
   * operators, or parentheses, or numbers indicating surface or cell identities.
   *
   * @param The list of geometry tokens in the input file, as a list of strings that were 
   *        separated by white space in the original file.
   */
  void retokenize_geometry( const token_list_t& tokens ){
    for(token_list_t::const_iterator i = tokens.begin(); i!=tokens.end(); ++i){
      const std::string& token = *i;
      
      size_t j = 0;
      while( j < token.length() ){

        char cj = token.at(j);

        switch(cj){
          
          // the following macro pushes an intersect token onto the geom list
          // if the end of that list indicates that one is needed
#define IMPLICIT_INTERSECT() do{                                \
            if(geom.size()){                                    \
              geom_list_entry_t &t = geom.at(geom.size()-1);    \
              if( is_num_token(t) || t.first == RPAREN ){       \
                geom.push_back( make_geom_entry( INTERSECT ) ); \
              }}} while(0) 
          
        case '(': 
          IMPLICIT_INTERSECT();
          geom.push_back(make_geom_entry(LPAREN)); j++;
          break;
          
        case ')':
          geom.push_back(make_geom_entry(RPAREN)); j++;
          break;
          
        case '#':
          IMPLICIT_INTERSECT();
          geom.push_back(make_geom_entry(COMPLEMENT)); j++; 
          break;
          
        case ':':
          geom.push_back(make_geom_entry(UNION)); j++; 
          break;
          
        default: // a number
          // the number refers to a cell if the previous token is a complement
          bool is_cell = geom.size() && ((geom.at(geom.size()-1)).first == COMPLEMENT);
          IMPLICIT_INTERSECT();
          assert(isdigit(cj) || cj == '+' || cj == '-' );
          size_t end = token.find_first_not_of("1234567890-+.",j);
          assert(j != end);

          std::string numstr( token, j, end-j );
          const char* numstr_c = numstr.c_str();
          char* p;
          int num = strtol( numstr_c, &p, 10 );

          if( *p == '.' ){
            // This is a macrobody facet
            assert( !is_cell );

            int facet = strtol( p+1, NULL, 10 );
            assert( facet > 0 && facet <= 8 );

            // storage of macrobody facets: multiply cell number by ten, add facet number
            num *= 10;
            // don't add a positive facet number to a negative cell numer
            num += (num > 0) ? facet : -facet;
            geom.push_back( make_geom_entry( MBODYFACET, num ) );
          }
          else{
            geom.push_back( make_geom_entry( is_cell ? CELLNUM : SURFNUM, num ));
          }

          j += (end-j);
          break;
#undef IMPLICIT_INTERSECT

        }
        
      } 
    }
    
    if( OPT_DEBUG ) std::cout << tokens << " -> " << geom << std::endl;
    
  }
示例#16
0
文件: config.c 项目: Zabrane/SPOCP
int
read_config(char *file, srv_t * srv)
{
	FILE           *fp;
	char            s[LINEBUF], *cp, *sp, pluginname[256];
	char            section = 0, *dbname = 0, *dbload = 0;
	unsigned int    n = 0;
	long            lval;
	int             i;
	plugin_t       *plugins, *pl = 0;
	dback_t        *dbp = 0;
	const conf_com_t *ccp;
	spocp_result_t  r;

	/*
	 * should never be necessary 

	if (!srv->root)
		srv->root = ruleset_new(0);
	 */

	if (!srv->root->db)
		srv->root->db = db_new();

	plugins = srv->plugin;

	if ((fp = fopen(file, "r")) == NULL) {
		traceLog(LOG_ERR,
		    "Could not find or open the configuration file \"%s\"", file);
		return 0;
	}

	while (fgets(s, LINEBUF, fp)) {
		n++;
		rmcrlf(s);

		if (*s == 0 || *s == '#')
			continue;

		/*
		 * New section 
		 */
		if (*s == '[') {

			cp = find_balancing(s + 1, '[', ']');
			if (cp == 0) {
				traceLog(LOG_ERR, err_msg, n, "Section specification");
				return 0;
			}

			*cp = 0;
			sp = s + 1;

			if (strcasecmp(sp, "server") == 0)
				section = SYSTEM;
			else if (strcasecmp(sp, "dback") == 0)
				section = DBACK;
			else {
				section = PLUGIN;
				strlcpy(pluginname, sp, sizeof( pluginname));
				pl = 0;
			}

			continue;
		}

		/*
		 * Within a section The directives are of the form: 
		 * key *SP * "=" *SP val *(*SP val)
		 * val = 1*nonspacechar / '"' char '"' 
		 */

		rm_lt_sp(s, 1);	/* remove leading and trailing blanks */

		/*
		 * empty line or comment 
		 */
		if (*s == 0 || *s == '#')
			continue;

		cp = strchr(s, '=');
		if (cp == 0) {
			traceLog(LOG_ERR, err_msg, n, "syntax error");
			continue;
		}

		sp = cp;
		for (*cp++ = '\0'; *cp && (*cp == ' ' || *cp == '\t'); cp++)
			*cp = '\0';
		for (sp--; sp >= s && (*sp == ' ' || *sp == '\t'); sp--)
			*sp = '\0';

		/*
		 * no key, not good 
		 */
		if (*s == '\0')
			continue;

		switch (section) {
		case SYSTEM:
			for (i = 1; keyword[i]; i++)
				if (strcasecmp(keyword[i], s) == 0)
					break;

			if (keyword[i] == 0) {
#ifdef HAVE_SASL
				if((strncmp("sasl_", s, 5) == 0))
					add_overflow_directive(s, cp);
				else
#endif
				traceLog(LOG_ERR, err_msg, n, "Unknown keyword");
				continue;
			}

			switch (i) {
			case RULEFILE:
				if (srv->rulefile)
					free(srv->rulefile);
				srv->rulefile = Strdup(cp);
				break;

			case CERTIFICATE:
				if (srv->certificateFile)
					free(srv->certificateFile);
				srv->certificateFile = Strdup(cp);
				break;

			case PRIVATEKEY:
				if (srv->privateKey)
					free(srv->privateKey);
				srv->privateKey = Strdup(cp);
				break;

			case CALIST:
				if (srv->caList)
					free(srv->caList);
				srv->caList = Strdup(cp);
				break;

			case DHFILE:
				if (srv->dhFile)
					free(srv->dhFile);
				srv->dhFile = Strdup(cp);
				break;

			case ENTROPYFILE:
				if (srv->SslEntropyFile)
					free(srv->SslEntropyFile);
				srv->SslEntropyFile = Strdup(cp);
				break;

			case PASSWD:
				if (srv->passwd)
					free(srv->passwd);
				srv->passwd = Strdup(cp);
				break;

			case LOGGING:
				if (srv->logfile)
					free(srv->logfile);
				srv->logfile = Strdup(cp);
				break;

			case TIMEOUT:
				if (numstr(cp, &lval) == SPOCP_SUCCESS) {
					if (lval >= 0 && lval <= YEAR)
						srv->timeout =
						    (unsigned int) lval;
					else {
						traceLog(LOG_ERR, err_msg, n,
							 "Value out of range");
						srv->timeout = DEFAULT_TIMEOUT;
					}
				} else {
					traceLog(LOG_ERR, err_msg, n,
						 "Non numeric value");
					srv->timeout = DEFAULT_TIMEOUT;
				}

				break;

			case UNIXDOMAINSOCKET:
				if (srv->uds)
					free(srv->uds);
				srv->uds = Strdup(cp);
				break;

			case PORT:
				if (numstr(cp, &lval) == SPOCP_SUCCESS) {
					if (lval > 0L && lval < 65536) {
						srv->port =
						    (unsigned int) lval;
					} else {
						traceLog(LOG_ERR, err_msg, n,
							 "Number out of range");
						srv->port = DEFAULT_PORT;
					}
				} else {
					traceLog(LOG_ERR, err_msg, n,
						 "Non numeric value");
				}
				break;

			case NTHREADS:
				if (numstr(cp, &lval) == SPOCP_SUCCESS) {
					if (lval <= 0) {
						traceLog(LOG_ERR, err_msg, n,
							 "Value out of range");
						return 0;
					} else {
						int             level =
						    (int) lval;

						srv->threads = level;
					}
				} else {
					traceLog(LOG_ERR, err_msg, n,
						 "Non numeric specification");
					return 0;
				}
				break;

			case SSLVERIFYDEPTH:
				if (numstr(cp, &lval) == SPOCP_SUCCESS) {
					if (lval > 0L) {
						srv->sslverifydepth =
						    (unsigned int) lval;
					} else {
						traceLog(LOG_ERR, err_msg, n,
							 "number out of range");
						srv->sslverifydepth = 0;
					}
				} else {
					traceLog(LOG_ERR, err_msg, n,
						 "Non numeric value");
				}
				break;

			case PIDFILE:
				if (srv->pidfile)
					Free(srv->pidfile);
				srv->pidfile = Strdup(cp);
				break;

			case MAXCONN:
				if (numstr(cp, &lval) == SPOCP_SUCCESS) {
					if (lval > 0L) {
						srv->nconn =
						    (unsigned int) lval;
					} else {
						traceLog(LOG_ERR, err_msg, n,
							 "Number out of range");
						srv->sslverifydepth = 0;
					}
				} else {
					traceLog(LOG_ERR, err_msg, n,
						 "Non numeric value");
				}
				break;

#ifdef HAVE_SSL
			case CLIENTCERT:
				if (strcasecmp(cp, "none") == 0)
					srv->clientcert = NONE;
				else if (strcasecmp(cp, "demand") == 0)
					srv->clientcert = DEMAND;
				else if (strcasecmp(cp, "hard") == 0)
					srv->clientcert = HARD;

				break;
#endif
			case NAME:
				if (srv->name)
					Free(srv->name);
				srv->name = Strdup(cp);
				break;
			}
			break;

		case PLUGIN:
			if (pl == 0) {
				if (strcmp(s, "load") != 0) {
					traceLog(LOG_ERR, err_msg, n,
						 "First directive in plugin sector has to be \"load\"");
					section = 0;
				}

				if ((pl =
				     plugin_load(plugins, pluginname,
						 cp)) == 0)
					section = 0;
				else {
					/*
					 * The last one is placed last 
					 */
					for (; pl->next; pl = pl->next);
				}

				if (plugins == 0)
					plugins = pl;
			} else {
				if (strcmp(s, "poolsize") == 0) {
					if (numstr(cp, &lval) == SPOCP_SUCCESS) {
						if (lval <= 0) {
							traceLog(LOG_ERR, err_msg, n,
								 "Value out of range");
						} else {
							int             level =
							    (int) lval;

							if (pl->dyn == 0)
								pl->dyn =
								    pdyn_new
								    (level);
							if (pl->dyn->size == 0)
								pl->dyn->size =
								    level;
						}
					} else {
						traceLog(LOG_ERR, err_msg, n,
							 "Non numeric specification");
					}
				} else if (strcmp(s, "cachetime") == 0) {
					if (plugin_add_cachedef(pl, cp) == FALSE )
						traceLog(LOG_ERR, err_msg, n,
							 "Cachetime def");
				} else if (pl->ccmds == 0) {	/* No
								 * directives
								 * allowed */
					traceLog(LOG_ERR, err_msg, n,
						 "Directive where there should not be one");
				} else {
					for (ccp = pl->ccmds; ccp; ccp++) {
						int np=0, j;
						char **arr;

						arr = strchop(cp,&np);

						for (j=0; j<np; j++)
							traceLog(LOG_ERR, "%s:%s",
							    cp, arr[j]);

						if (strcmp(ccp->name, s) == 0) {
							r = ccp->func(&pl->
								      conf,
								      ccp->
								      cmd_data,
								      np, arr);
							if (r != SPOCP_SUCCESS) {
								traceLog
								    (LOG_ERR, err_msg,
								     n,
								     ccp->
								     errmsg);
							}
							charmatrix_free( arr );
							break;
						}
					}
					if (ccp == 0) {
						traceLog(LOG_ERR,err_msg, n,
							 "Unknown directive");
					}
				}
			}
			break;

		case DBACK:
			if (dbp == 0) {
				if (strcmp(s, "name") == 0) {
					dbname = Strdup(cp);
					if (dbname && dbload) {
						dbp =
						    dback_load(dbname, dbload);
						free(dbname);
						free(dbload);
					}
				} else if (strcmp(s, "load") == 0) {
					dbload = Strdup(cp);
					if (dbname && dbload) {
						dbp =
						    dback_load(dbname, dbload);
						free(dbname);
						free(dbload);
					}
				} else
					traceLog(LOG_ERR,err_msg, n,
						 "Unknown directive");
			} else {
				for (ccp = dbp->ccmds; ccp && *ccp->name;
				     ccp++) {
					if (strcmp(ccp->name, s) == 0) {
						r = ccp->func(&dbp->conf,
							      ccp->cmd_data, 1,
							      &cp);
						if (r != SPOCP_SUCCESS) {
							traceLog(LOG_ERR,err_msg, n,
								 ccp->errmsg);
						}
						break;
					}
				}
				if (ccp == 0) {
					traceLog(LOG_ERR,err_msg, n,
						 "Unknown directive");
				}
			}
			break;
		}
	}

	fclose(fp);

	if (srv->pidfile == 0)
		srv->pidfile = Strdup("spocd.pid");
	if (srv->timeout == 0)
		srv->timeout = DEFAULT_TIMEOUT;
	if (srv->threads == 0)
		srv->threads = DEFAULT_NTHREADS;
	if (srv->sslverifydepth == 0)
		srv->sslverifydepth = DEFAULT_SSL_DEPTH;

	srv->plugin = plugins;
	srv->dback = dbp;

	return 1;
}