Пример #1
0
static int
printAttribute(D4printer* out, NCD4node* attr, int depth)
{
    int ret = NC_NOERR;
    int i = 0;
    char* fqn = NULL;

    INDENT(depth); CAT("<Attribute");
    printXMLAttributeName(out,"name",attr->name);
    if(attr->basetype->subsort <=  NC_MAX_ATOMIC_TYPE)
	printXMLAttributeName(out,"type",attr->basetype->name);
    else {
	printXMLAttributeName(out,"type",(fqn = NCD4_makeFQN(attr->basetype)));
    }
    CAT(">\n");
    depth++;
    for(i=0;i<nclistlength(attr->attr.values);i++) {
	printValue(out,(const char*)nclistget(attr->attr.values,i),depth);
	CAT("\n");
    }
    depth--;
    INDENT(depth);
    CAT("</Attribute>");

    nullfree(fqn);
    return THROW(ret);
}
Пример #2
0
static const char *axes_mask(uint8_t flags, char *buf, size_t maxbuf,
			     int isEnable)
{

#define CAT(x) \
  { if (buf[0]) strncat(buf, ", ", maxbuf); \
    strncat(buf, (x), maxbuf); }

	if (!buf || !maxbuf)
		return(NULL);

	buf[0] = '\0';

	if (isEnable) strncat(buf, (flags & 0x80) ? "+" : "-", maxbuf);

	if (flags != (uint8_t)0)
	{
	     if (flags & 0x01) CAT("X");
	     if (flags & 0x02) CAT("Y");
	     if (flags & 0x04) CAT("Z");
	     if (flags & 0x08) CAT("A");
	     if (flags & 0x10) CAT("B");
	}
	else
	     strncat(buf, "<NO AXES>", maxbuf);

	return(buf);

#undef CAT
}
Пример #3
0
static int
printMetaData(D4printer* out, NCD4node* node, int depth)
{
    int ret = NC_NOERR;
    int i;

    if(nclistlength(node->dims) > 0) {
	for(i=0;i<nclistlength(node->dims);i++) {
	    NCD4node* dim = (NCD4node*)nclistget(node->dims,i);
	    printDimref(out,dim,depth);
	    CAT("\n");
	}
    }
    if(nclistlength(node->maps) > 0) {
	for(i=0;i<nclistlength(node->maps);i++) {
	    NCD4node* mapref = (NCD4node*)nclistget(node->maps,i);
	    printMap(out,mapref,depth);
	    CAT("\n");
	}
     }
    if(nclistlength(node->attributes) > 0) {
	for(i=0;i<nclistlength(node->attributes);i++) {
	    NCD4node* attr = (NCD4node*)nclistget(node->attributes,i);
	    printAttribute(out,attr,depth);
	    CAT("\n");
	}
    }
    return THROW(ret);
}
Пример #4
0
static int
printValue(D4printer* out, const char* value, int depth)
{
    int ret = NC_NOERR;
    INDENT(depth);
    CAT("<Value");
    printXMLAttributeString(out,"value",value);
    CAT("/>");
    return THROW(ret);
}
Пример #5
0
static int
printXMLAttributeAtomics(D4printer* out, char* name, union ATOMICS* value, nc_type type)
{
    int ret = NC_NOERR;
    CAT(" "); CAT(name); CAT("=\"");
    atomicsToString(out,value,type);	
    CAT(ncbytescontents(out->tmp));
    CAT("\"");
    return THROW(ret);
}
Пример #6
0
int main()
{
	int a=CAT(2,5);
	float f = CAT(10,e2);
	char str[20]= strcat(Veda,Solutions);			

	printf(" a = %d\n",a);
	printf(" f = %f\n",f);
	printf(" str = %s\n",str);
}	
Пример #7
0
static int
printMap(D4printer* out, NCD4node* mapref, int depth)
{
    char* fqn = NULL;
    INDENT(depth);
    CAT("<Map");
    printXMLAttributeName(out, "name", (fqn=NCD4_makeFQN(mapref)));
    CAT("/>");
    nullfree(fqn);
    return THROW(NC_NOERR);
}
Пример #8
0
void CMyLcd::Beep(const SPlayTone* play,bool fromProgMem)
{
	if (fromProgMem)
	{
		CBeep<CAT(BOARDNAME, _LCD_BEEPER)>::PlayPGM(play);
	}
	else
	{
		CBeep<CAT(BOARDNAME, _LCD_BEEPER)>::Play(play);
	}
}
static int concat(void)
{
#define CAT(res, args) do { char *str = ne_concat args; \
ONCMP(str, res); \
ne_free(str); } while (0)
    CAT("alphabeta", ("alpha", "beta", NULL));
    CAT("alpha", ("alpha", "", "", NULL));
    CAT("", ("", NULL));
    CAT("", ("", "", "", NULL));
    CAT("alpha", ("", "a", "lph", "", "a", NULL));
    return OK;    
}
Пример #10
0
static int
printGroup(D4printer* out, NCD4node* node, int depth)
{
    int ret = NC_NOERR;
    INDENT(depth);
    CAT("<Group");
    printXMLAttributeName(out,"name",node->name);
    CAT(">\n");
    depth++;
    ret = printGroupBody(out,node,depth);
    depth--;
    INDENT(depth);
    CAT("</Group>");
    return THROW(ret);	   
}	
Пример #11
0
static int
printXMLAttributeName(D4printer* out, char* name, const char* value)
{
    int ret = NC_NOERR;
    char* escaped = NULL;

    if(name == NULL) return THROW(ret);
    if(value == NULL) value = "";
    CAT(" "); CAT(name); CAT("=\"");
    /* add xml entity escaping */
    escaped = NCD4_entityescape(value);
    CAT(escaped);
    CAT("\"");
    nullfree(escaped);
    return THROW(ret);
}
Пример #12
0
void CMyLcd::Init()
{
#if  defined(USE_RAMPS14)
	_lcd_numaxis=5;
#endif

	CBeep<(CAT(BOARDNAME, _LCD_BEEPER))>::Init();
	
	super::Init();

	_rotarybutton.SetPin(ROTARY_EN1,ROTARY_EN2);
	_rotarypushbutton.SetPin(ROTARY_ENC,ROTARY_ENC_ON);

	CHAL::pinModeInputPullUp(CAT(BOARDNAME,_LCD_KILL_PIN));

	_rotarybutton.Tick();
}
Пример #13
0
static int
printDataset(D4printer* out, NCD4node* node, int depth)
{
    int ret = NC_NOERR;
    CAT("<Dataset\n");
    depth++;
    INDENT(depth);
    printXMLAttributeName(out,"name",node->group.datasetname);
    CAT("\n");
    INDENT(depth);
    printXMLAttributeName(out,"dapVersion",node->group.dapversion);
    CAT("\n");
    INDENT(depth);
    printXMLAttributeName(out,"dmrVersion",node->group.dmrversion);
    CAT("\n");
    INDENT(depth);
    printXMLAttributeName(out,"xmlns","http://xml.opendap.org/ns/DAP/4.0#");
    CAT("\n");
    INDENT(depth);
    printXMLAttributeName(out,"xmlns:dap","http://xml.opendap.org/ns/DAP/4.0#");
    depth--;
    CAT(">\n");
    depth++;
    ret = printGroupBody(out,node,depth);
    depth--;
    INDENT(depth);
    CAT("</Dataset>");
    return THROW(ret);	   
}
Пример #14
0
static void library_init(void)
{
    /* This seems to be a no-op, but it makes the GHCRTS envvar work. */
    static char *argv[] = { STR(MODULE) ".so", 0 }, **argv_ = argv;
    static int argc = 1;
    printf("Loading library OfxPlugin and initializing rts\n");
    hs_init(&argc, &argv_);
    hs_add_root(CAT(__stginit_, MODULE));
}
Пример #15
0
static void library_init(void)
{
    /* This seems to be a no-op, but it makes the GHCRTS envvar work. */
    static char *argv[] = { STR(CalculatorFinance) ".so", 0 }, **argv_ = argv;
    static int argc = 1;
 
    hs_init(&argc, &argv_);
    hs_add_root(CAT(__stginit_, CalculatorFinance));
}
Пример #16
0
void	ft_get_tets(t_tet *tets, t_piece **pieces)
{
	while (*pieces)
	{	
		tets->max = ft_min(*pieces);
		tets->blocs = CAT((*pieces));
		tets->pos = 0;
		tets->ident = -1;
		pieces++;
		tets++;
	}
}
Пример #17
0
int main(int argc, char *argv[]) {
	int i;

	license(stdout, "/* ", " * ", " */");

	printf("#ifndef CATALOGUES_H_INCLUDED\n"
		"#define CATALOGUES_H_INCLUDED\n\n");

	printf("static const unsigned char opcode_breaks[KIND_MAX] = {\n\t");
	for (i = 0; i < sizeof(opcode_breaks)/sizeof(opcode_breaks[0]); ++i)
		printf("%d, ", opcode_breaks[i]);
	printf("\n};\n\n");

	CAT(stats_catalogue);
	CAT(prob_catalogue);
	CAT(mode_catalogue);
	CONVERSION(conv_catalogue);
	CAT(clear_catalogue);
	CAT(displ_catalogue);
	CAT(more_catalogue);

	fprintf(stderr, "# $Rev$\n" );
	fprintf(stderr, "version=%c%c\n", VERSION_STRING[0], VERSION_STRING[2]);
        fprintf(stderr, "maxsteps=%d\n", 1);
        fprintf(stderr, "maxlibsteps=%d\n", 1);
	dump_opcodes(stderr, 0);

	printf( "/* Total number of catalogue entries %d\n"
		" * Total number of conversion entries %d\n"
		" * Total number of alpha entries %d\n"
		" */\n", total_cat, total_conv, total_alpha);
	printf("#endif\n");
	return 0;
}
Пример #18
0
int main(){
        //     FILE * dump = popen("od -t d4","w");
    uint8_t input[102400];
    size_t inputsize;

    NailArena arena;
    pos p;
    inputsize = fread(input, 1, sizeof(input), stdin);
    //fprintf(stderr, "inputsize=%zu\ninput=", inputsize);
//    fwrite(input, 1, inputsize, stderr);
//    fprintf(stderr,"\n\n\n");
//    n_trace_init(&test,4096,4096);
    NailArena_init(&arena,4096);
//    inputsize *= 8;
    XYZZY *object; 
    object = CAT(parse_,XYZZY)(&arena,input,inputsize);
    if(object){
            printf("\n Successfully parsed! Trying to generate\n");
            const char *buf;
            size_t siz;
            NailStream stream;
            NailOutStream_init(&stream,4096);
           if(CAT(gen_,XYZZY)(&arena,&stream,object)<0)
           {
                              fprintf(stderr,"Could not generate\n");
                              exit(-1);
                              }
            buf = NailOutStream_buffer(&stream,&siz);
            printf("Output:\n");
            fwrite(buf,1,siz,stdout);
            printf("\nEnd of output;\n");
            if(siz != inputsize)
                    return -1;
    }   
    else {
            fprintf(stderr, "Could not parse\n");
            exit(-1);
    }
    return 0;
}
Пример #19
0
SDLeftStat_t * ADDSUFFIX(dleft_stat) (SDLeftArray_t * const dleftobj, FILE *stream) {
fprintf(stderr,"[!]Count with[%s]\n",CAT(THETYPE));
    SDLeftStat_t *pSDLeftStat = malloc(sizeof(SDLeftStat_t));
    THETYPE * const pCountHistArray = calloc(sizeof(THETYPE),1+dleftobj->maxCountSeen);
    size_t totalDLAsize = dleftobj->SubItemCount * dleftobj->itemByte * dleftobj->ArraySize;
    //size_t firstlevelDLAitemsize = SDLA_ITEMARRAY*dleftobj->itemByte;
    const unsigned char * const pDLA = dleftobj->pDLA;
    THETYPE Item_CountBits=0;  // set value in case SDLA_ITEMARRAY*dleftobj->itemByte == 0 (EP ?)
    uint128_t theItem;
    for (size_t i=0;i<totalDLAsize;i+=dleftobj->itemByte) {
        //const unsigned char * pChunk = pDLA + i;
        theItem = 0;
        for (uint_fast8_t j=0;j<dleftobj->itemByte;j++) {
            theItem |= ((uint128_t)*(pDLA + i + j)) << (j*8u);
        }
        Item_CountBits = theItem & dleftobj->Item_CountBitMask;
        ++pCountHistArray[Item_CountBits];
        //++HistSum;
    }
    //THETYPE HistSum=0;    // HistSum == dleftobj->ItemInsideAll
    DILTYPE HistSumSquared=0;
    double SStd;    // We need to return in a fixed type for printf
    for (size_t p=1;p<=dleftobj->maxCountSeen;p++) {
        //HistSum += pCountHistArray[p];
        HistSumSquared += pCountHistArray[p] * pCountHistArray[p];
    }
    //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
    SStd = sqrtl( ( (long double)HistSumSquared-((long double)dleftobj->ItemInsideAll*(long double)dleftobj->ItemInsideAll/(long double)dleftobj->maxCountSeen) ) / (long double)(dleftobj->maxCountSeen -1) );
    pSDLeftStat->HistSStd = SStd;
    pSDLeftStat->HistMean = (double)dleftobj->ItemInsideAll / (double)dleftobj->maxCountSeen;
    pSDLeftStat->HistMaxCntVal = 1; //later
    pSDLeftStat->HistMaxHistVal = 1; //later
    fprintf(stream,"#Kmer_real_count: %ld\n#Kmer_count_hist: %ld\n#Kmer_depth_mean: %f\n#Kmer_depth_sStd: %f\n\n#Kmer_frequence\tHist_value\tKmer_count\tHist_ratio\n",
        dleftobj->ItemInsideAll,dleftobj->maxCountSeen,pSDLeftStat->HistMean,SStd);
    for (size_t p=1;p<=dleftobj->maxCountSeen;p++) {
        fprintf(stream,"%zu\t%lu\t%lu\t%g\n",p,(uint64_t)pCountHistArray[p],
            (uint64_t)pCountHistArray[p]*(uint64_t)p,(double)pCountHistArray[p]/(double)dleftobj->ItemInsideAll);
    }
    free(pCountHistArray);
    // deal(*pextree);
    return pSDLeftStat;
}
Пример #20
0
static int
printGroupBody(D4printer* out, NCD4node* node, int depth)
{
    int ret = NC_NOERR;
    int i,ngroups,nvars,ntypes,ndims,nattrs;

    ngroups = nclistlength(node->groups);
    nvars = nclistlength(node->vars);
    ntypes = nclistlength(node->types);
    ndims = nclistlength(node->dims);
    nattrs = nclistlength(node->attributes);

    if(ndims > 0) {
	INDENT(depth);
	CAT("<Dimensions>\n");
	depth++;
	for(i=0;i<nclistlength(node->dims);i++) {
	    NCD4node* dim = (NCD4node*)nclistget(node->dims,i);
	    printNode(out,dim,depth);
	    CAT("\n");
	}
	depth--;
	INDENT(depth);
	CAT("</Dimensions>\n");
    }
    if(ntypes > 0) {
	INDENT(depth);
	CAT("<Types>\n");
	depth++;
	for(i=0;i<nclistlength(node->types);i++) {
	    NCD4node* type = (NCD4node*)nclistget(node->types,i);
	    if(type->subsort <= NC_MAX_ATOMIC_TYPE) continue;
	    printNode(out,type,depth);
	    CAT("\n");
	}
	depth--;
	INDENT(depth);
	CAT("</Types>\n");
    }
    if(nvars > 0) {
	INDENT(depth);
	CAT("<Variables>\n");
	depth++;
	for(i=0;i<nclistlength(node->vars);i++) {
	    NCD4node* var = (NCD4node*)nclistget(node->vars,i);
	    printNode(out,var,depth);
	}
	depth--;
	INDENT(depth);
	CAT("</Variables>\n");
    }
    if(nattrs > 0) {
	for(i=0;i<nclistlength(node->attributes);i++) {
	    NCD4node* attr = (NCD4node*)nclistget(node->attributes,i);
	    printAttribute(out,attr,depth);
	    CAT("\n");
	}
    }
    if(ngroups > 0) {
	INDENT(depth);
	CAT("<Groups>\n");
	depth++;
	for(i=0;i<nclistlength(node->groups);i++) {
	    NCD4node* g = (NCD4node*)nclistget(node->groups,i);
	    printNode(out,g,depth);
	    CAT("\n");
	}
	depth--;
	INDENT(depth);
	CAT("</Groups>\n");
    }
    return THROW(ret);
}
Пример #21
0
static int
printNode(D4printer* out, NCD4node* node, int depth)
{
    int ret = NC_NOERR;
    int i;
    char* fqn = NULL;

    switch (node->sort) {
    case NCD4_GROUP:
	if(node->group.isdataset)
	    printDataset(out,node,depth);
	else
	    printGroup(out,node,depth);
	break;

    case NCD4_DIM:
	INDENT(depth);
	CAT("<Dimension");
	if(node->name != NULL)
	    printXMLAttributeName(out, "name", node->name);
	printXMLAttributeSize(out, "size", node->dim.size);
	if(node->dim.isunlimited)
	    printXMLAttributeString(out, UCARTAGUNLIM, "1");
	CAT("/>");
	break;

    case NCD4_TYPE:
	switch (node->subsort) {
	default: break;
	case NC_OPAQUE:
	    INDENT(depth); CAT("<Opaque");
	    ncbytesclear(out->tmp);
	    printXMLAttributeName(out, "name", node->name);
	    if(node->opaque.size > 0)
	        printXMLAttributeSize(out, "size", node->opaque.size);
	    CAT("/>");
	    break;	    
	case NC_ENUM:
	    INDENT(depth); CAT("<Enumeration");
	    printXMLAttributeName(out, "name", node->name);
	    if(node->basetype->subsort <= NC_MAX_ATOMIC_TYPE)
		printXMLAttributeName(out, "basetype", node->basetype->name);
	    else {
		char* fqn = NULL;
		printXMLAttributeName(out, "basetype", (fqn = NCD4_makeFQN(node->basetype)));
		nullfree(fqn);
	    }
	    CAT(">\n");
	    depth++;
	    for(i=0;i<nclistlength(node->en.econsts);i++) {
		NCD4node* ec = (NCD4node*)nclistget(node->en.econsts,i);
		INDENT(depth);
		CAT("<EnumConst");
		printXMLAttributeName(out, "name", ec->name);
		printXMLAttributeAtomics(out, "value", &ec->en.ecvalue, node->basetype->subsort);
		CAT("/>\n");
	    }
	    depth--;
	    INDENT(depth); CAT("</Enumeration>");
	    break;
	case NC_STRUCT:
	    INDENT(depth);
	    CAT("<Structure");
	    printXMLAttributeName(out, "name", node->name);
	    CAT(">\n");
	    depth++;
	    for(i=0;i<nclistlength(node->vars);i++) {
		NCD4node* field = (NCD4node*)nclistget(node->vars,i);
		printVariable(out,field,depth);
		CAT("\n");
	    }
	    if((ret=printMetaData(out,node,depth))) goto done;
	    depth--;
	    INDENT(depth);
	    CAT("</Structure>");
	    break;
	case NC_SEQ:
	    INDENT(depth);
	    CAT("<Vlen");
	    printXMLAttributeName(out, "name", node->name);
	    printXMLAttributeName(out, "type", (fqn=NCD4_makeFQN(node->basetype)));
	    if(hasMetaData(node)) {
		CAT(">\n");
		depth++;
		if((ret=printMetaData(out,node,depth))) goto done;
		depth--;
		INDENT(depth);
		CAT("</Vlen>");
	    } else
	        CAT("/>");
  	    break;
        } break;
    case NCD4_VAR: /* Only top-level vars are printed here */
	if(ISTOPLEVEL(node)) {
  	    if((ret=printVariable(out,node,depth))) goto done;
	    CAT("\n");
	}
	break;

    default: abort(); break;
    }
done:
    nullfree(fqn);
    return THROW(ret);
}
Пример #22
0
    http://www.boost.org/

    Copyright (c) 2001-2006 Hartmut Kaiser. Distributed under the Boost
    Software License, Version 1.0. (See accompanying file
    LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/

//O --variadics

// Tests macro expansion order in conjunction with the need to skip expansion 
// of the same macro as it is currently expanded.

#define CONCAT(a, b) a ## b
#define CONCAT_INDIRECT() CONCAT

//R #line 20 "t_1_004.cpp"
//R CONCAT(1, 2)
CONCAT(CON, CAT)(1, 2)
//R #line 23 "t_1_004.cpp"
//R CONCAT(1, 2)
CONCAT(CON, CAT(1, 2))
//R #line 26 "t_1_004.cpp"
//R 12
CONCAT(CONCAT_, INDIRECT)()(1, 2)
//R #line 29 "t_1_004.cpp"
//R CONCAT(1, 2)
CONCAT(CONCAT_, INDIRECT())(1, 2)
//R #line 32 "t_1_004.cpp"
//R 1 CONCAT(2, 3)
CONCAT(1, CONCAT(2, 3))
Пример #23
0
void timer_print(){
  printf("---\n");
  printf("TOTAL     : %6.2f s \n", timer_read(TOTAL));
  printf("---\n");
#define CAT(c_) timer_read(c_), timer_read(c_)/timer_read(TOTAL)*100
#ifdef _BLOCKING
  printf("LU       : %6.2f s (%4.2f%%)\n", CAT(LU));
  printf(" - PANEL   : %6.2f s (%4.2f%%)\n", CAT(PANEL));
  printf("   - PIVOT   : %6.2f s (%4.2f%%)\n", CAT(PANEL_PIVOT));
  printf("   - SWAP    : %6.2f s (%4.2f%%)\n", CAT(PANEL_SWAP));
  printf("   - DSCAL   : %6.2f s (%4.2f%%)\n", CAT(PANEL_DSCAL));
  printf("   - DGER    : %6.2f s (%4.2f%%)\n", CAT(PANEL_DGER));
  printf("   - DTRSM   : %6.2f s (%4.2f%%)\n", CAT(PANEL_DTRSM));
  printf("   - DGEMM   : %6.2f s (%4.2f%%)\n", CAT(PANEL_DGEMM));
  printf(" - SWAP    : %6.2f s (%4.2f%%)\n", CAT(SWAP));
  printf(" - DTRSM   : %6.2f s (%4.2f%%)\n", CAT(DTRSM));
  printf(" - DGEMM   : %6.2f s (%4.2f%%)\n", CAT(DGEMM));
  printf("DSOLVE   : %6.2f s (%4.2f%%)\n", CAT(DSOLVE));
#else
  printf("LU        : %6.2f s (%4.2f%%)\n", CAT(LU));
  printf(" - PIVOT    : %6.2f s (%4.2f%%)\n", CAT(PANEL_PIVOT));
  printf(" - SWAP     : %6.2f s (%4.2f%%)\n", CAT(SWAP));
  printf(" - PANEL    : %6.2f s (%4.2f%%)\n", CAT(PANEL));
  printf(" - UPDATE   : %6.2f s (%4.2f%%)\n", CAT(PANEL_DGER));
  printf("DSOLVE    : %6.2f s (%4.2f%%)\n", CAT(DSOLVE));
#endif
  printf("---\n");
  fflush(stdout);
}
Пример #24
0
int main(void) {

    /*
    # Comments are replaced by spaces.
    */
    {
        int/* */a = 1;
        assert(a == 1);
    }

    /*
    # Newline in macro

    # Multiline macro

        Impossible:

        - http://stackoverflow.com/questions/10419530/multi-line-preprocessor-macros
        - http://stackoverflow.com/questions/98944/how-to-generate-a-newline-in-a-cpp-macro
    */

    /*
    # #define

        You can put preprocessor directives anywhere
        but putting on global scope is the more standard and simple approach

        Use defines with discretion: they make it much harder to debug!
    */
    {

        /*
        Syntax: the line must start with `#`,
        but there can be spaces after it to give indentation.
        */
        {
#define SPACE_AFTER_HASH 1
            assert(SPACE_AFTER_HASH == 1);
        }

        /*
        # Constants

            Use sparingly.

            - constants have scope
            - produce meaningful error messages
        */
        {
            {
#define CTE 1
                assert(CTE == 1);
            }

            /*
            Don't forget to protect arithmetic operations
            or associativity may get you.
            */
            {
                /* Use parenthesis or order of operation might destroy you: */
#define PROTECT_FAIL 1 + 1
                assert(PROTECT_FAIL * 2 == 3);
#define PROTECT (1 + 1)
                assert(PROTECT * 2 == 4);
            }

            /*
            Expansion is lazy: macros do not expand in `#define`
            but only when the macro is used.
            */
            {
#define LAZY0 LAZY1
#define LAZY1 LAZY2
#define LAZY2 2
                assert(LAZY2 == 2);
            }
        }

        /* # Redefine macros */
        {
            /* Cannot redefine macros directly. */
            {
#define REDEFINE_FAIL 1
                /* ERROR */
                /*#define REDEFINE_FAIL 2*/
            }

            /* Must first undef. */
            {
#define REDEFINE 1
#undef REDEFINE
#define REDEFINE 2
                assert(REDEFINE == 2);
            }
        }

        /* # Functions (preprocessor) */
        {
            /*
            Generates:

                assert(1 + 1 == 2);

            Not:

                assert(2 == 2);
            */
            {
#define SUM(x, y) x + y
                assert(SUM(1, 1) == 2);
            }

            /*
            # Comma protection

                The macro engine has to do some kind of parsing to determine that
                the comma of the function (1) is not the comma of the macro (2).

                What it seems to do is simply check if the comma is between pairs of:

                - parenthesis
                - double quotes

                and if yes ignore it.

                This does not however cover C++ template parameters, and `assert` + template is a common break case
                http://stackoverflow.com/questions/4496842/pass-method-with-template-arguments-to-a-macro

                Pure C also has cases in which it is necessary to use parenthesis,
                for example when the comma operator is used.

                A more complicated case in which protecting parenthesis break:
                http://stackoverflow.com/questions/9187614/how-do-i-have-a-comma-inside-braces-inside-a-macro-argument-when-parentheses-cau
            */
            {
                assert(SUM(int_int_int_func(1, 1), 1) == 3);
                /*                           ^   ^ */
                /*                           1   2 */

                int i = 1;
                assert(SUM((i++, i), 1) == 3);
                /*                 ^ */
                /*                 comma operator */

                /* ERROR must protect the comma operator. */
                /*assert(SUM(i++, i, 1) == 3);*/

#define CAT(x, y) x y
                /* Strings are treated as a single token, so commas inside strings are fine. */
                assert(strcmp(CAT("1,", "2"), "1,2") == 0);
            }

            /*
            # Function inside argument

                - http://stackoverflow.com/questions/163365/how-do-i-make-a-c-macro-behave-like-a-function
                - http://stackoverflow.com/questions/154136/do-while-and-if-else-statements-in-c-c-macros
            */
            {
                /* TODO */
            }

            /*
            # Argument inside string

            # #
            */
            {
                /* Strings are treated as single tokens, so arguments don't expand by default. */
#define ARG_IN_STRING_BAD(x) "x"
                assert(strcmp(ARG_IN_STRING_BAD("a"), "x") == 0);

                /*
                Solution: use # stringification.

                It simply adds "" around the argument and expands it.
                */
#define STRINGIFY(x) #x
                assert(strcmp(STRINGIFY(a), "a") == 0);
                assert(strcmp(STRINGIFY(""), "\"\"") == 0);
                /* ERROR: parsing fails because of unbalanced `"`. */
                /*assert(strcmp(STRINGIFY("), "\"") == 0);*/

#define STRINGIFY_CAT(x) "a" STRINGIFY(x) "c"
                assert(strcmp(STRINGIFY_CAT(b), "abc") == 0);

                /*
                This fails however for macro arguments, which don't expand when `# arg` is used!

                Solution Use a two step expansion process...

                - http://stackoverflow.com/questions/8283596/whats-the-difference-between-these-two-macros?lq=1
                - http://stackoverflow.com/questions/6742501/whats-the-exact-step-of-macro-expanding

                TODO what is the rationale for that exception of not expanding upon `#`?
                */
#define STRINGIFY_ARG a
                assert(strcmp(STRINGIFY(STRINGIFY_ARG), "STRINGIFY_ARG") == 0);
            }

            /* # variadic macro functions */
            {
                char s[4];
#define SPRINTF(string, format, ...) sprintf(string, format, __VA_ARGS__)
                SPRINTF(s, "%c%c", 'a', 'b');
                assert(strcmp(s, "ab") == 0);
            }

#if __STDC_VERSION__ >= 199901L
            /*
            # Empty macro arguments

                http://stackoverflow.com/questions/7666344/are-empty-macro-arguments-legal-in-c11
            */
            {
#define EMPTY(x) x ## 2 ==
                assert(EMPTY(1) 12);

                /*
                TODO if the argument is empty,
                does it still count for concatenation?
                */
                assert(EMPTY() 2);
            }
#endif
        }

        /*
        # #include

            It is possible, and very confusing, to include any type of file,
            not just header files.
        */
        {
            int i = 0;
#include "preprocessor.inc"
            assert(i == 1);
        }
    }

    /*
    # #undef

        Undo a previous define.
    */
    {
#define UNDEF_TEST 1
#undef UNDEF_TEST
#ifdef UNDEF_TEST
# error
#endif
    }

    /*
    # Concatenate

    # Double hash preprocessor operator

    # ##

        `##` allows to concatenate a preprocessor function arguments without spaces between them.
    */
    {
        /* Basic. */
        {
#define CAT_NO_SPACE(x) x ## d
            int CAT_NO_SPACE(c_) = 1;
            assert(c_d == 1);
        }

        /*
        Multiple concatenation insanity:
        http://stackoverflow.com/questions/1489932/c-preprocessor-and-concatenation
        */
        {
            {
#define CAT_FAIL_VAR 0
#define CAT_FAIL x ## CAT_FAIL_VAR
                int CAT_FAIL = 1;
                assert(xCAT_FAIL_VAR == 1);
            }

            /* Solution. */
            {
#define CAT_VAR 0
#define PASTER(x,y) x ## y
#define EVALUATOR(x,y) PASTER(x,y)
#define CAT_OK EVALUATOR(x, CAT_VAR)
                int CAT_OK = 1;
                assert(x0 == 1);
            }
        }
    }

    /*
    # #ifdef

        Check if preprocessor variable is defined.

        # or and ifdef

            http://stackoverflow.com/questions/965700/c-preprocessor-testing-definedness-of-multiple-macros

            Almost the same as `#if defined()`,
            except you can use `#if defined()` with `|| on a single line as:

                #if defined(X) || defined(Y)

            while

                #ifdef(X) || ifdef(Y)
                #ifdef X || Y

            compiles but does not do what you expect:
            TODO legal?

            For `&&`, we could get away with:

                #ifdef(X)
                #ifdef(Y)

            but there is no alternative for `||`.

    # #ifndef

        Negation of ifdef.

    # #defined

        Like ifdef, but more flexible
        as you can use it inside `#if` with boolean operators.
    */
    {
#ifdef COMMANDLINE
        /* gcc -DCOMMANDLINE c.c */
        puts("C");
#else
        /* gcc c.c */
        puts("no C");
#endif
    }

    /*
    # #if

    # #else

    # #elif

        The preprocessor can do certain integer arithmetic operations such as: +, -, ==, <.
    */
    {
#if 1 == 0
# error
#elif 1 == 1
#else
# error
#endif

#define INIF 1
#if INIF + 1 == 2
#else
# error
#endif

#if 16 == 0x10
#else
# error
#endif

        /* Undefined evaluate equal. */
        {
#if NOT_DEFINED == NOT_DEFINED2
#else
# error
#endif
        }

        /*
        Cannot compare strings directly!
        http://stackoverflow.com/questions/2335888/how-to-compare-string-in-c-conditional-preprocessor-directives
        Always define to integers.
        */
#define STR1 1
#define STR2 2
#define STR STR1

#if STR == STR1
#elif STR == STR2
# error
#endif
    }

    /*
    # && preprocessor

    # and preprocessor
    */
#define C 1
#if defined(C) && C > 0
#else
# error
#endif

    /*
    # #error

        Print an error message to stderr and stop compilation.

        Useful to enforce preprocessor conditions.
    */
    {
        /* #error "the error message" */
    }

    /*
    # null directive

        A `#` followed by newline is ignored.
    */
    {
#
    }

    /*
    # #pragma

        C99 specifies that:

            # pragma X Y Z ...

        -   if `X != STDC`, does something implementation defined, and therefore not portable.

            Examples: `#pragma once`

        -   else, then the statement must take a form:

                # pragma STDC FP_CONTRACT on-off-switch
                # pragma STDC FENV_ACCESS on-off-switch
                # pragma STDC CX_LIMITED_RANGE on-off-switch

            all of which are portable.
    */

    /*
    # #line

        Set the line and optionally filename that is seen by `__FILE__` and `__LINE__`.
    */
    {
        /*#line 1*/
    }

    /*
    # Predefined preprocessor macros

    # Standard preprocessor defines

        Some preprocessor vars are automatically defined by certain compilers
        although they are not c standards. Those are not discussed here.

        List of standard defines: http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html

        List all them on GCC:

            gcc -dM -E - < /dev/null | sort

        Sample output:

            #define _LP64 1
            #define _STDC_PREDEF_H 1
            #define __ATOMIC_ACQUIRE 2
            #define __ATOMIC_ACQ_REL 4
            #define __ATOMIC_CONSUME 1
            #define __ATOMIC_HLE_ACQUIRE 65536
            #define __ATOMIC_HLE_RELEASE 131072
            #define __ATOMIC_RELAXED 0
            #define __ATOMIC_RELEASE 3
            #define __ATOMIC_SEQ_CST 5
    */
    {
        /*
        # STDC_VERSION

        # __STDC_VERSION__

            String representing version of the c std lib. Format: yyyymm (base 10).

            Some values:

            - C11: 201112L
            - C99: 199901L

            http://sourceforge.net/p/predef/wiki/Standards/

            Apperas undefined in C99
        */
        {
            printf("__STDC_VERSION__ = %li\n", __STDC_VERSION__);
        }

        /*
        # __STDC__

        # STDC

            1 if the implementation is conforming, 0 otherwise.

            TODO check: on GCC, 1 with `-std=cXX`, 0 with `-std=gnuXX`.
        */
        {
            printf("__STDC__ = %d\n", __STDC__);
        }

        /*
        # __STDC_HOSTED__

        # STDC

            Indicate if the compilation is hosted or not.

        # Hosted

        # Freestanding

            Concept defined in ANSI C.

            Basically, a freestanding implementation does not need to provide an stdlib.

            In GCC, controlled by the `-ffreestainding` option.
        */
        {
            printf("__STDC_HOSTED__ = %d\n", __STDC_HOSTED__);
        }


        /*
        # __cplusplus

            Defined only if using C++ compiler.

            C99 says that C must not define it.
        */
#ifdef __cplusplus
        printf("__cplusplus\n");
#endif

        /*
        # __FILE__

            Absolute or relative path of current file.
        */
        {
            printf("__FILE__ = %s\n", __FILE__);
        }

        /*
        # __LINE__

            Current source code line.

            Useful for debugging.

            If in a `.h`, position inside the `.h` before inclusion.
        */
        {
            printf("__LINE__ = %d\n", __LINE__);
        }

        printf("__DATE__ = %s\n", __DATE__);

        printf("__TIME__ = %s\n", __TIME__);

#ifdef __WIN32__
        /* Automatically defined by certain compilers on windows: */
        /* TODO gcc specific or not? if yes move out of here. */
        puts("__WIN32__");
#endif

#ifdef _LIBC
        /* TODO what is this */
        /* TODO gcc specific or not? if yes move out of here. */
        puts("_LIBC");
#endif

#ifdef __ILP32__
        /* TODO what is this */
        /* TODO gcc specific or not? if yes move out of here. */
        puts("__ILP32__");
#endif

#ifdef ___X32_SYSCALL_BIT
        /* TODO what is this */
        /* TODO gcc specific or not? if yes move out of here. */
        puts("___X32_SYSCALL_BIT");
#endif

        /*
        # IEEE-754

            IEC 60559 has the same contents as the IEEE 754-2008,
            Outside of the C standard it is commonly known by the IEEE name, or simply as IEEE floating point.

            IEEE dates from 1985.

        # __STDC_IEC_559__

        # IEC 60599

            Standard on which floating point formats and operations should be available
            on an implementation, and how they should work.

            Good overview wiki article: <http://en.wikipedia.org/wiki/IEEE_floating_point>

            Many CUPs implement large parts of IEC 60599, which C implementations can use if available.

            The C standard specifies that implementing the IEC 60599 is not mandatory.

            If the macro `__STDC_IEC_559__` is defined this means that the implementation is compliant
            to the interface specified in Annex F of the C11 standard.

            C99 introduced many features which allow greater conformance to IEC 60599.
        */
        {
#ifdef __STDC_IEC_559__
            puts("__STDC_IEC_559__");

            /*
            I think it guaranteed by the standard on annex F:

            - The float type matches the IEC 60559 single format.
            - The double type matches the IEC 60559 double format.
            - The long double type matches an IEC 60559 extended format,307) else a
              non-IEC 60559 extended format, else the IEC 60559 double format.
            */
            assert(sizeof(float) == 4);
            assert(sizeof(double) == 8);
#endif
        }

        /*
        # Expand macro to another macro

            Nope:
            http://stackoverflow.com/questions/1262063/preprocessor-macro-expansion-to-another-preprocessor-directive
        */

#ifndef __STDC_NO_ATOMICS__
        /* Indicates no C11 support for `_Atomic` and `<stdatomic.h>`. */
        puts("__STDC_NO_ATOMICS__");
#else
#include <stdatomic.h>
        _Atomic int i;
#endif
    }

    return EXIT_SUCCESS;
}
Пример #25
0
elemptr symmodel::get_model_widx( const vector<string>& parsed, const vector<size_t>& idx, const vector<elemptr>& trace )
  {
    //I start with it already parsed.
    //If parsed.size() == 0, I simply return this (with an index?)
    //The empty string indicates "this" model? No, when I parse it, I need to sep it, so an empty, will return in a zero-parse, of size zero, or nothing?
    //Either way, would result in same, so return ;)
    if( parsed.size() == 0 || parsed[0].compare("") == 0 )
      {
	fprintf(stdout, "FOUND MODEL! [%s]\n", buildpath().c_str() );
	elemptr t = elemptr( shared_from_this(), idx );
	return t;
      }
    else
      {
	fprintf(stdout, "Model [%s], attempting to find model name [%s] widx (note, trace size is [%lu])\n", buildpath().c_str(), CAT(parsed, "/").c_str(), trace.size());
      }
    //This is the next model I will go into
    string submodel = parsed[0];
    vector<string> remainder( parsed.begin()+1, parsed.end() ); //same as remainder, remainder.erase(0);
    
    //REV: This is where I should iterate up the tree! This is the issue.
    vector<size_t> mlocs = find_model( submodel );
    vector<size_t> hlocs = find_hole( submodel );
    
    //At this point, we are finding the hole etc. normally.
    if( mlocs.size() >= 1 )
      {
	if( mlocs.size() > 1 )
	  {
	    fprintf(stderr, "WTF found more than one in getmodelwidx\n");
	    exit(1);
	  }
	
	size_t mloc = mlocs[0];
	//add model to trace? I guess? It is a submodel, so it is not necessary I guess? But it helps it find submodels I guess? Could this cause a problem?

	fprintf(stdout, "Model [%s], going through submodel [%s] to find [%s]\n", buildpath().c_str(), models[mloc]->localname.c_str(), CAT(remainder, "/").c_str() );
	
	std::shared_ptr<symmodel> nextmodel = models[mloc];

	//Don't add to trace because if same model, parent will cause infinite loop in combin with trace.
	//However
	//Problem is if I go through a hole, and the hole is the same model, that is the main problem
	vector<elemptr> newtrace = trace;
	//size_t idx_in_submodel = idx; //no change, b/c submodel.
	vector<size_t> idx_in_submodel = idx; //no change, b/c submodel.
	//newtrace.push_back( elemptr( shared_from_this(), idx ) );
	
	return nextmodel->get_model_widx( remainder, idx_in_submodel, newtrace );
      }
    else if( hlocs.size() >= 1 )
      {
	if( hlocs.size() > 1)
	  {
	    fprintf(stderr, "WTF more than one HOLE found in getmodelwidx\n");
	    exit(1);
	  }
	

	size_t hloc = hlocs[0];
	fprintf(stdout, "Model [%s], going through hole [%s] to find [%s]\n", buildpath().c_str(), holes[hloc].name.c_str(), CAT(remainder, "/").c_str());
	if( holes[ hloc ].members.size() != 1 )
	  {
	    fprintf(stderr, "ERROR in get_model_widx, getting [%s] from HOLE, but hole [%s] has size [%lu], but it should be 1\n", submodel.c_str(), holes[hloc].name.c_str(), holes[hloc].members.size() );
	    exit(1);
	  }

	//REV: so in the case it does not exist yet, we have a problem?
	std::shared_ptr<symmodel> nextmodel = holes[hloc].members[0];
	
	if( check_same_toplevel_model( nextmodel ) )
	  {
	    //Dont add to trace because its same model so infinite loop with going to parent.x
	    vector<elemptr> newtrace = trace;
	    //size_t idx_in_submodel = idx; //no change, b/c submodel.
	    vector<size_t> idx_in_submodel = idx; //no change, b/c submodel.
	    //newtrace.push_back( elemptr( shared_from_this(), idx ) );
	    
	    return nextmodel->get_model_widx( remainder, idx_in_submodel, newtrace );
	  }
	else //not same toplevel model
	  {
	    //I NEED TO GO THROUGH A CORRESPONDENCE

	    fprintf(stdout, "REV: about to go through a corresp to get a non-same model thing through a hole...\n");
	    //std::shared_ptr<corresp> mycorresp;
	    auto mycorresp  = getcorresp( nextmodel );
	    if( !mycorresp )
	      {
		fprintf(stderr, "REV: getcorresp in get_model_widx, failed, no such corresp exists between [%s] and [%s]\n", buildpath().c_str(), nextmodel->buildpath().c_str());
		exit(1);
	      }
	    
	    
	    //REV; SANITY, if corresp not allocated yet, just return 0.
	    //size_t idx_in_submodel = 0;
	    vector<size_t> idx_in_submodel(1,0);
	    
	    //REV; Don't check this here, check this in the corresp struct? I.e. return dummy data if it is not existing yet (or exit?)
	    if(mycorresp->isinit())
	      {
		fprintf(stdout, "Corresp is INIT!!!! Will attempt a GETALL...\n");
		//REV: TODO HERE, just return it directly, with new IDX_IN_SUBMODEL ;0
		//REV: this is it!!! This is where I 
		vector<size_t> sanity = mycorresp->getall( idx );
		
		fprintf(stdout, "Attempted to GETALL from the corresp!\n");
		/*if( sanity.size() != 1 )
		  {
		  fprintf(stderr, "SANITY check for corresp during access failed! Expected corresp for idx [%lu] of model [%s] to have only 1 corresponding element in model [%s], but it had [%lu]\n", idx, buildpath().c_str(), nextmodel->buildpath().c_str(), sanity.size() );
		  exit(1);
		  }
		  size_t idx_in_submodel = sanity[0]; //no change, b/c submodel.
		*/

		idx_in_submodel = sanity;
	      }
	    
	    vector<elemptr> newtrace = trace;
	    newtrace.push_back( elemptr( shared_from_this(), idx ) );

	    fprintf(stdout, "About to get next model with idx...\n");
	    auto toret = nextmodel->get_model_widx( remainder, idx_in_submodel, newtrace );
	    fprintf(stdout, "FINISHED About to get next model with idx...\n");
	    return toret;
	  }
      } //end if not found in HOLES (or submodels)
    else
      {
	fprintf(stdout, "Model [%s], walking up to parent [%s] to find [%s]\n", buildpath().c_str(), parent->localname.c_str(), CAT(parsed, "/").c_str());
	//Else, try to bubble up to ROOT.
	if( parent && (parent->parent) )
	  {
	    std::shared_ptr<symmodel> nextmodel = parent;
	    
	    vector<elemptr> newtrace = trace;
	    //size_t idx_in_submodel = idx; //no change, b/c submodel.
	    vector<size_t> idx_in_submodel = idx; //no change, b/c submodel.
	    //newtrace.push_back( elemptr( shared_from_this(), idx ) );
	    
	    return nextmodel->get_model_widx( parsed, idx_in_submodel, newtrace );
	  }
	else if(  parent && !(parent->parent) )
	  {
	    //Couldn't find it! Return empty elemptr...bad.
	    elemptr ep;
	    return ep;
	  }
	else
	  {
	    fprintf(stderr, "REV; this should never happen weird, Neither parent nor parent->parent? In searching for model with idx. Exit\n");
	    if( parent )
	      {
		fprintf( stderr, "Parent of me [%s] exists and is [%s]\n", buildpath().c_str(), parent->buildpath().c_str() );
	      }
	    else
	      {
		fprintf( stderr, "Parent does not exist... (note current model is [%s])!\n", buildpath().c_str() );
	      }
	    exit(1);
	  }
      } //couldn't find in "else" (i.e. not in this model, so try bubbling up parents)
    
    if(trace.size() == 0)
      {
	fprintf(stderr, "Trace size zero. This should never happen (should have been caught above)\n");
	exit(1);
      }

    //REV: Did I mess something up? First it should check through all guys directly to see if it is same model? I.e. if target model matches b/c we can use that idx.
    fprintf(stdout, "Couldn't find model [%s] in previous model trace [%s], so moving to next! (trace size is [%lu])\n", CAT(parsed,"/").c_str(), buildpath().c_str(), trace.size() );
    
    //Move back model and try again?
    vector<elemptr> newtrace = trace;
    //size_t idx_in_submodel = newtrace[ newtrace.size() - 1].idx; //end of trace.
    vector<size_t> idx_in_submodel = newtrace[ newtrace.size() - 1].idx; //end of trace.
    std::shared_ptr<symmodel> nextmodel = newtrace[ newtrace.size() - 1].model;
    newtrace.pop_back();

    fprintf(stdout, "Will now try to run with new trace size [%lu]\n", newtrace.size() );
    return nextmodel->get_model_widx( parsed, idx_in_submodel, newtrace );
    
  } //end get_model_widx
Пример #26
0
static int
printVariable(D4printer* out, NCD4node* var, int depth)
{
    int ret = NC_NOERR;
    NCD4node* basetype = var->basetype;
    char* fqn = NULL;

    INDENT(depth); CAT("<");
    switch (var->subsort) {
    default:
	CAT(basetype->name);
	printXMLAttributeName(out, "name", var->name);
	break;
    case NC_ENUM:
	CAT("Enum");
	printXMLAttributeName(out, "name", var->name);
	printXMLAttributeName(out, "enum", (fqn=NCD4_makeFQN(basetype)));
	break;
    case NC_OPAQUE:
	CAT("Opaque");
	printXMLAttributeName(out, "name", var->name);
	printXMLAttributeName(out, "type", (fqn=NCD4_makeFQN(basetype)));
	break;
    case NC_SEQ:
	CAT("Seq");
	printXMLAttributeName(out, "name", var->name);
	printXMLAttributeName(out, "type", (fqn=NCD4_makeFQN(basetype)));
	break;
    case NC_STRUCT:
	CAT("Struct");
	printXMLAttributeName(out, "name", var->name);
	printXMLAttributeName(out, "type", (fqn=NCD4_makeFQN(basetype)));
	break;
    }
    if(hasMetaData(var)) {
	CAT(">\n");
	depth++;
	if((ret=printMetaData(out,var,depth))) goto done;
	depth--;
	INDENT(depth); CAT("</");
	if(basetype->subsort == NC_ENUM)
	    CAT("Enum");
	else if(basetype->subsort == NC_OPAQUE)
	    CAT("Opaque");
	else if(basetype->subsort == NC_STRUCT)
	    CAT("Struct");
	else if(basetype->subsort == NC_SEQ)
	    CAT("Sequence");
	else
	    CAT(basetype->name);
	CAT(">");
    } else
	CAT("/>");
done:
    nullfree(fqn);
    return THROW(ret);
}