<commit_before>#ifndef __BH_VE_CPU_SPECIALIZER
#define __BH_VE_CPU_SPECIALIZER

#include <ctemplate/template.h>

void specializer_init()
{
    ctemplate::mutable_default_template_cache()->SetTemplateRootDirectory(template_path);
    ctemplate::LoadTemplate("license.tpl",  ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("include.tpl",  ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("range.tpl",    ctemplate::STRIP_BLANK_LINES);

    ctemplate::LoadTemplate("reduction.1d.tpl", ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("reduction.2d.tpl", ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("reduction.3d.tpl", ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("reduction.nd.tpl", ctemplate::STRIP_BLANK_LINES);

    ctemplate::LoadTemplate("traverse.1d.tpl",      ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("traverse.2d.tpl",      ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("traverse.3d.tpl",      ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("traverse.nd.ddd.tpl",  ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("traverse.nd.tpl",      ctemplate::STRIP_BLANK_LINES);
    ctemplate::mutable_default_template_cache()->Freeze();
}

void symbolize(bh_instruction *instr, bh_sij_t &sij) {

    char symbol_c[500]; // String representation buffers
    char dims_str[10];

    sij.instr = instr;
    switch (sij.instr->opcode) {    // [OPCODE_SWITCH]

        case BH_NONE:                                   // System opcodes
        case BH_DISCARD:
        case BH_SYNC:
        case BH_FREE:
        case BH_USERFUNC:                               // Extensions
            break;

        case BH_ADD_REDUCE:                             // Reductions
        case BH_MULTIPLY_REDUCE:
        case BH_MINIMUM_REDUCE:
        case BH_MAXIMUM_REDUCE:
        case BH_LOGICAL_AND_REDUCE:
        case BH_BITWISE_AND_REDUCE:
        case BH_LOGICAL_OR_REDUCE:
        case BH_LOGICAL_XOR_REDUCE:
        case BH_BITWISE_OR_REDUCE:
        case BH_BITWISE_XOR_REDUCE:
            sij.ndims = sij.instr->operand[1].ndim;     // Dimensions
            sij.lmask = bh_layoutmask(sij.instr);       // Layout mask
            sij.tsig  = bh_typesig(sij.instr);          // Type signature

            if (sij.ndims <= 3) {                       // String representation
                sprintf(dims_str, "%ldD", sij.ndims);
            } else {
                sprintf(dims_str, "ND");
            }
            sprintf(symbol_c, "%s_%s_%s_%s",
                bh_opcode_text(sij.instr->opcode),
                bh_typesig_to_shorthand(sij.tsig),
                dims_str,
                bh_layoutmask_to_shorthand(sij.lmask)
            );

            sij.symbol = string(symbol_c);
            break;

        case BH_RANGE:

            sij.ndims = sij.instr->operand[0].ndim;     // Dimensions
            sij.lmask = bh_layoutmask(sij.instr);       // Layout mask
            sij.tsig  = bh_typesig(sij.instr);          // Type signature

            sprintf(symbol_c, "%s_%s_ND_%s",
                bh_opcode_text(sij.instr->opcode),
                bh_typesig_to_shorthand(sij.tsig),
                bh_layoutmask_to_shorthand(sij.lmask)
            );

            sij.symbol = string(symbol_c);
            break;

        default:                                        // Built-in

            sij.ndims = sij.instr->operand[0].ndim;     // Dimensions
            sij.lmask = bh_layoutmask(sij.instr);       // Layout mask
            sij.tsig  = bh_typesig(sij.instr);          // Type signature

            if (sij.ndims <= 3) {                       // String representation
                sprintf(dims_str, "%ldD", sij.ndims);
            } else {
                sprintf(dims_str, "ND");
            }
            sprintf(symbol_c, "%s_%s_%s_%s",
                bh_opcode_text(sij.instr->opcode),
                bh_typesig_to_shorthand(sij.tsig),
                dims_str,
                bh_layoutmask_to_shorthand(sij.lmask)
            );

            sij.symbol = string(symbol_c);
            break;
    }
}

string specialize(bh_sij_t &sij) {

    char template_fn[500];   // NOTE: constants like these are often traumatizing!

    bool cres = false;

    ctemplate::TemplateDictionary dict("codegen");
    ctemplate::TemplateDictionary include_dict("INCLUDE");

    switch (sij.instr->opcode) {                    // OPCODE_SWITCH

        case BH_RANGE:
            dict.SetValue("OPERATOR", bhopcode_to_cexpr(sij.instr->opcode));
            dict.SetValue("SYMBOL", sij.symbol);
            dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
            sprintf(template_fn, "range.tpl");

            cres = true;
            break;

        case BH_ADD_REDUCE:
        case BH_MULTIPLY_REDUCE:
        case BH_MINIMUM_REDUCE:
        case BH_MAXIMUM_REDUCE:
        case BH_LOGICAL_AND_REDUCE:
        case BH_BITWISE_AND_REDUCE:
        case BH_LOGICAL_OR_REDUCE:
        case BH_LOGICAL_XOR_REDUCE:
        case BH_BITWISE_OR_REDUCE:
        case BH_BITWISE_XOR_REDUCE:

            dict.SetValue("OPERATOR", bhopcode_to_cexpr(sij.instr->opcode));
            dict.SetValue("SYMBOL", sij.symbol);
            dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
            dict.SetValue("TYPE_A1", enum_to_ctypestr(sij.instr->operand[1].base->type));

            if (sij.ndims <= 3) {
                sprintf(template_fn, "reduction.%ldd.tpl", sij.ndims);
            } else {
                sprintf(template_fn, "reduction.nd.tpl");
            }

            cres = true;
            break;

        case BH_ADD:
        case BH_SUBTRACT:
        case BH_MULTIPLY:
        case BH_DIVIDE:
        case BH_POWER:
        case BH_GREATER:
        case BH_GREATER_EQUAL:
        case BH_LESS:
        case BH_LESS_EQUAL:
        case BH_EQUAL:
        case BH_NOT_EQUAL:
        case BH_LOGICAL_AND:
        case BH_LOGICAL_OR:
        case BH_LOGICAL_XOR:
        case BH_MAXIMUM:
        case BH_MINIMUM:
        case BH_BITWISE_AND:
        case BH_BITWISE_OR:
        case BH_BITWISE_XOR:
        case BH_LEFT_SHIFT:
        case BH_RIGHT_SHIFT:
        case BH_ARCTAN2:
        case BH_MOD:
        case BH_RANDOM:

            dict.SetValue("OPERATOR", bhopcode_to_cexpr(sij.instr->opcode));
            if ((sij.lmask & A2_CONSTANT) == A2_CONSTANT) {
                dict.SetValue("SYMBOL", sij.symbol);
                dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
                dict.SetValue("TYPE_A1", enum_to_ctypestr(sij.instr->operand[1].base->type));
                dict.SetValue("TYPE_A2", enum_to_ctypestr(sij.instr->constant.type));
                dict.ShowSection("a1_dense");
                dict.ShowSection("a2_scalar");
            } else if ((sij.lmask & A1_CONSTANT) == A1_CONSTANT) {
                dict.SetValue("SYMBOL", sij.symbol);
                dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
                dict.SetValue("TYPE_A1", enum_to_ctypestr(sij.instr->constant.type));
                dict.SetValue("TYPE_A2", enum_to_ctypestr(sij.instr->operand[2].base->type));
                dict.ShowSection("a1_scalar");
                dict.ShowSection("a2_dense");
            } else {
                dict.SetValue("SYMBOL", sij.symbol);
                dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
                dict.SetValue("TYPE_A1", enum_to_ctypestr(sij.instr->operand[1].base->type));
                dict.SetValue("TYPE_A2", enum_to_ctypestr(sij.instr->operand[2].base->type));
                dict.ShowSection("a1_dense");
                dict.ShowSection("a2_dense");

            }
            if ((sij.lmask == (A0_CONTIGUOUS + A1_CONTIGUOUS    + A2_CONTIGUOUS)) || \
                (sij.lmask == (A0_CONTIGUOUS + A1_CONSTANT + A2_CONTIGUOUS)) || \
                (sij.lmask == (A0_CONTIGUOUS + A1_CONTIGUOUS    + A2_CONSTANT))) {
                sprintf(template_fn, "traverse.nd.ddd.tpl");
            } else {
                if (sij.ndims<=3) {
                    sprintf(template_fn, "traverse.%ldd.tpl", sij.ndims);
                } else {
                    sprintf(template_fn, "traverse.nd.tpl");
                }
            }

            cres = true;
            break;

        case BH_ABSOLUTE:
        case BH_LOGICAL_NOT:
        case BH_INVERT:
        case BH_COS:
        case BH_SIN:
        case BH_TAN:
        case BH_COSH:
        case BH_SINH:
        case BH_TANH:
        case BH_ARCSIN:
        case BH_ARCCOS:
        case BH_ARCTAN:
        case BH_ARCSINH:
        case BH_ARCCOSH:
        case BH_ARCTANH:
        case BH_EXP:
        case BH_EXP2:
        case BH_EXPM1:
        case BH_LOG:
        case BH_LOG2:
        case BH_LOG10:
        case BH_LOG1P:
        case BH_SQRT:
        case BH_CEIL:
        case BH_TRUNC:
        case BH_FLOOR:
        case BH_RINT:
        case BH_ISNAN:
        case BH_ISINF:
        case BH_IDENTITY:

            dict.SetValue("OPERATOR", bhopcode_to_cexpr(sij.instr->opcode));
            if ((sij.lmask & A1_CONSTANT) == A1_CONSTANT) {
                dict.SetValue("SYMBOL", sij.symbol);
                dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
                dict.SetValue("TYPE_A1", enum_to_ctypestr(sij.instr->constant.type));
                dict.ShowSection("a1_scalar");
            } else {
                dict.SetValue("SYMBOL", sij.symbol);
                dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
                dict.SetValue("TYPE_A1", enum_to_ctypestr(sij.instr->operand[1].base->type));
                dict.ShowSection("a1_dense");
            }

            if ((sij.lmask == (A0_CONTIGUOUS + A1_CONTIGUOUS)) || \
                (sij.lmask == (A0_CONTIGUOUS + A1_CONSTANT))) {
                sprintf(template_fn, "traverse.nd.ddd.tpl");
            } else {

                if (sij.ndims<=3) {
                    sprintf(template_fn, "traverse.%ldd.tpl", sij.ndims);
                } else {
                    sprintf(template_fn, "traverse.nd.tpl");
                }

            }

            cres = true;
            break;

        default:
            printf("cpu-ve: Err=[Unsupported ufunc...]\n");
    }

    if (!cres) {
        throw runtime_error("cpu-ve: Failed specializing code.");
    }

    string sourcecode = "";
    ctemplate::ExpandTemplate("include.tpl", ctemplate::STRIP_BLANK_LINES, &include_dict, &sourcecode);
    ctemplate::ExpandTemplate(
        template_fn,
        ctemplate::STRIP_BLANK_LINES,
        &dict,
        &sourcecode
    );

    return sourcecode;
}

#endif

<commit_msg>cpu: Removed the deprecated BH_USERFUNC.<commit_after>#ifndef __BH_VE_CPU_SPECIALIZER
#define __BH_VE_CPU_SPECIALIZER

#include <ctemplate/template.h>

void specializer_init()
{
    ctemplate::mutable_default_template_cache()->SetTemplateRootDirectory(template_path);
    ctemplate::LoadTemplate("license.tpl",  ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("include.tpl",  ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("range.tpl",    ctemplate::STRIP_BLANK_LINES);

    ctemplate::LoadTemplate("reduction.1d.tpl", ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("reduction.2d.tpl", ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("reduction.3d.tpl", ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("reduction.nd.tpl", ctemplate::STRIP_BLANK_LINES);

    ctemplate::LoadTemplate("traverse.1d.tpl",      ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("traverse.2d.tpl",      ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("traverse.3d.tpl",      ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("traverse.nd.ddd.tpl",  ctemplate::STRIP_BLANK_LINES);
    ctemplate::LoadTemplate("traverse.nd.tpl",      ctemplate::STRIP_BLANK_LINES);
    ctemplate::mutable_default_template_cache()->Freeze();
}

void symbolize(bh_instruction *instr, bh_sij_t &sij) {

    char symbol_c[500]; // String representation buffers
    char dims_str[10];

    sij.instr = instr;
    switch (sij.instr->opcode) {    // [OPCODE_SWITCH]

        case BH_NONE:                                   // System opcodes
        case BH_DISCARD:
        case BH_SYNC:
        case BH_FREE:
            break;

        case BH_ADD_REDUCE:                             // Reductions
        case BH_MULTIPLY_REDUCE:
        case BH_MINIMUM_REDUCE:
        case BH_MAXIMUM_REDUCE:
        case BH_LOGICAL_AND_REDUCE:
        case BH_BITWISE_AND_REDUCE:
        case BH_LOGICAL_OR_REDUCE:
        case BH_LOGICAL_XOR_REDUCE:
        case BH_BITWISE_OR_REDUCE:
        case BH_BITWISE_XOR_REDUCE:
            sij.ndims = sij.instr->operand[1].ndim;     // Dimensions
            sij.lmask = bh_layoutmask(sij.instr);       // Layout mask
            sij.tsig  = bh_typesig(sij.instr);          // Type signature

            if (sij.ndims <= 3) {                       // String representation
                sprintf(dims_str, "%ldD", sij.ndims);
            } else {
                sprintf(dims_str, "ND");
            }
            sprintf(symbol_c, "%s_%s_%s_%s",
                bh_opcode_text(sij.instr->opcode),
                bh_typesig_to_shorthand(sij.tsig),
                dims_str,
                bh_layoutmask_to_shorthand(sij.lmask)
            );

            sij.symbol = string(symbol_c);
            break;

        case BH_RANGE:

            sij.ndims = sij.instr->operand[0].ndim;     // Dimensions
            sij.lmask = bh_layoutmask(sij.instr);       // Layout mask
            sij.tsig  = bh_typesig(sij.instr);          // Type signature

            sprintf(symbol_c, "%s_%s_ND_%s",
                bh_opcode_text(sij.instr->opcode),
                bh_typesig_to_shorthand(sij.tsig),
                bh_layoutmask_to_shorthand(sij.lmask)
            );

            sij.symbol = string(symbol_c);
            break;

        default:                                        // Built-in

            sij.ndims = sij.instr->operand[0].ndim;     // Dimensions
            sij.lmask = bh_layoutmask(sij.instr);       // Layout mask
            sij.tsig  = bh_typesig(sij.instr);          // Type signature

            if (sij.ndims <= 3) {                       // String representation
                sprintf(dims_str, "%ldD", sij.ndims);
            } else {
                sprintf(dims_str, "ND");
            }
            sprintf(symbol_c, "%s_%s_%s_%s",
                bh_opcode_text(sij.instr->opcode),
                bh_typesig_to_shorthand(sij.tsig),
                dims_str,
                bh_layoutmask_to_shorthand(sij.lmask)
            );

            sij.symbol = string(symbol_c);
            break;
    }
}

string specialize(bh_sij_t &sij) {

    char template_fn[500];   // NOTE: constants like these are often traumatizing!

    bool cres = false;

    ctemplate::TemplateDictionary dict("codegen");
    ctemplate::TemplateDictionary include_dict("INCLUDE");

    switch (sij.instr->opcode) {                    // OPCODE_SWITCH

        case BH_RANGE:
            dict.SetValue("OPERATOR", bhopcode_to_cexpr(sij.instr->opcode));
            dict.SetValue("SYMBOL", sij.symbol);
            dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
            sprintf(template_fn, "range.tpl");

            cres = true;
            break;

        case BH_ADD_REDUCE:
        case BH_MULTIPLY_REDUCE:
        case BH_MINIMUM_REDUCE:
        case BH_MAXIMUM_REDUCE:
        case BH_LOGICAL_AND_REDUCE:
        case BH_BITWISE_AND_REDUCE:
        case BH_LOGICAL_OR_REDUCE:
        case BH_LOGICAL_XOR_REDUCE:
        case BH_BITWISE_OR_REDUCE:
        case BH_BITWISE_XOR_REDUCE:

            dict.SetValue("OPERATOR", bhopcode_to_cexpr(sij.instr->opcode));
            dict.SetValue("SYMBOL", sij.symbol);
            dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
            dict.SetValue("TYPE_A1", enum_to_ctypestr(sij.instr->operand[1].base->type));

            if (sij.ndims <= 3) {
                sprintf(template_fn, "reduction.%ldd.tpl", sij.ndims);
            } else {
                sprintf(template_fn, "reduction.nd.tpl");
            }

            cres = true;
            break;

        case BH_ADD:
        case BH_SUBTRACT:
        case BH_MULTIPLY:
        case BH_DIVIDE:
        case BH_POWER:
        case BH_GREATER:
        case BH_GREATER_EQUAL:
        case BH_LESS:
        case BH_LESS_EQUAL:
        case BH_EQUAL:
        case BH_NOT_EQUAL:
        case BH_LOGICAL_AND:
        case BH_LOGICAL_OR:
        case BH_LOGICAL_XOR:
        case BH_MAXIMUM:
        case BH_MINIMUM:
        case BH_BITWISE_AND:
        case BH_BITWISE_OR:
        case BH_BITWISE_XOR:
        case BH_LEFT_SHIFT:
        case BH_RIGHT_SHIFT:
        case BH_ARCTAN2:
        case BH_MOD:
        case BH_RANDOM:

            dict.SetValue("OPERATOR", bhopcode_to_cexpr(sij.instr->opcode));
            if ((sij.lmask & A2_CONSTANT) == A2_CONSTANT) {
                dict.SetValue("SYMBOL", sij.symbol);
                dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
                dict.SetValue("TYPE_A1", enum_to_ctypestr(sij.instr->operand[1].base->type));
                dict.SetValue("TYPE_A2", enum_to_ctypestr(sij.instr->constant.type));
                dict.ShowSection("a1_dense");
                dict.ShowSection("a2_scalar");
            } else if ((sij.lmask & A1_CONSTANT) == A1_CONSTANT) {
                dict.SetValue("SYMBOL", sij.symbol);
                dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
                dict.SetValue("TYPE_A1", enum_to_ctypestr(sij.instr->constant.type));
                dict.SetValue("TYPE_A2", enum_to_ctypestr(sij.instr->operand[2].base->type));
                dict.ShowSection("a1_scalar");
                dict.ShowSection("a2_dense");
            } else {
                dict.SetValue("SYMBOL", sij.symbol);
                dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
                dict.SetValue("TYPE_A1", enum_to_ctypestr(sij.instr->operand[1].base->type));
                dict.SetValue("TYPE_A2", enum_to_ctypestr(sij.instr->operand[2].base->type));
                dict.ShowSection("a1_dense");
                dict.ShowSection("a2_dense");

            }
            if ((sij.lmask == (A0_CONTIGUOUS + A1_CONTIGUOUS    + A2_CONTIGUOUS)) || \
                (sij.lmask == (A0_CONTIGUOUS + A1_CONSTANT + A2_CONTIGUOUS)) || \
                (sij.lmask == (A0_CONTIGUOUS + A1_CONTIGUOUS    + A2_CONSTANT))) {
                sprintf(template_fn, "traverse.nd.ddd.tpl");
            } else {
                if (sij.ndims<=3) {
                    sprintf(template_fn, "traverse.%ldd.tpl", sij.ndims);
                } else {
                    sprintf(template_fn, "traverse.nd.tpl");
                }
            }

            cres = true;
            break;

        case BH_ABSOLUTE:
        case BH_LOGICAL_NOT:
        case BH_INVERT:
        case BH_COS:
        case BH_SIN:
        case BH_TAN:
        case BH_COSH:
        case BH_SINH:
        case BH_TANH:
        case BH_ARCSIN:
        case BH_ARCCOS:
        case BH_ARCTAN:
        case BH_ARCSINH:
        case BH_ARCCOSH:
        case BH_ARCTANH:
        case BH_EXP:
        case BH_EXP2:
        case BH_EXPM1:
        case BH_LOG:
        case BH_LOG2:
        case BH_LOG10:
        case BH_LOG1P:
        case BH_SQRT:
        case BH_CEIL:
        case BH_TRUNC:
        case BH_FLOOR:
        case BH_RINT:
        case BH_ISNAN:
        case BH_ISINF:
        case BH_IDENTITY:

            dict.SetValue("OPERATOR", bhopcode_to_cexpr(sij.instr->opcode));
            if ((sij.lmask & A1_CONSTANT) == A1_CONSTANT) {
                dict.SetValue("SYMBOL", sij.symbol);
                dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
                dict.SetValue("TYPE_A1", enum_to_ctypestr(sij.instr->constant.type));
                dict.ShowSection("a1_scalar");
            } else {
                dict.SetValue("SYMBOL", sij.symbol);
                dict.SetValue("TYPE_A0", enum_to_ctypestr(sij.instr->operand[0].base->type));
                dict.SetValue("TYPE_A1", enum_to_ctypestr(sij.instr->operand[1].base->type));
                dict.ShowSection("a1_dense");
            }

            if ((sij.lmask == (A0_CONTIGUOUS + A1_CONTIGUOUS)) || \
                (sij.lmask == (A0_CONTIGUOUS + A1_CONSTANT))) {
                sprintf(template_fn, "traverse.nd.ddd.tpl");
            } else {

                if (sij.ndims<=3) {
                    sprintf(template_fn, "traverse.%ldd.tpl", sij.ndims);
                } else {
                    sprintf(template_fn, "traverse.nd.tpl");
                }

            }

            cres = true;
            break;

        default:
            printf("cpu-ve: Err=[Unsupported ufunc...]\n");
    }

    if (!cres) {
        throw runtime_error("cpu-ve: Failed specializing code.");
    }

    string sourcecode = "";
    ctemplate::ExpandTemplate("include.tpl", ctemplate::STRIP_BLANK_LINES, &include_dict, &sourcecode);
    ctemplate::ExpandTemplate(
        template_fn,
        ctemplate::STRIP_BLANK_LINES,
        &dict,
        &sourcecode
    );

    return sourcecode;
}

#endif

<|endoftext|>


<commit_before>#include "Zero.hpp"

#include "Funcs.hpp"

/*
 * Implements gsetvar vnds function.
 * gsetvar var mod val
 * Modifier is '=' '+' or '-' in script, simplify to ('-':-1, '=':0, '+':1).
 * MAY need to be UTF8 friendly
 */

void op_setvar(char* var, int* modifier, char* value) {
	if (GetData()->if_fail != 0)
		return;

	int value_r = 0, ret;
	if(value == NULL)
		ret = 0;
	else
		ret = sscanf(value, "%d", &value_r);

	if(ret == 0) { // value is a variable not a number
		if(*modifier == 0) {
			GetData()->s_flags[0][std::string(var)] = GetData()->s_flags[0][std::string(value)];
		}
		else if (*modifier == -1) {
			GetData()->s_flags[0][std::string(var)] -= GetData()->s_flags[0][std::string(value)];
		}
		else if (*modifier == 1) {
			GetData()->s_flags[0][std::string(var)] += GetData()->s_flags[0][std::string(value)];
		}
	}
	else {
		if(*modifier == 0) {
			GetData()->s_flags[0][std::string(var)] = value_r;
		}
		else if (*modifier == -1) {
			GetData()->s_flags[0][std::string(var)] -= value_r;
		}
		else if (*modifier == 1) {
			GetData()->s_flags[0][std::string(var)] += value_r;
		}
		else if (*modifier == -2) {
			// There's a rare case on program start where a resetall
			// happens.

			if(!strcmp(var, "~")) {
				// We'll handle it by searching through and deleting all non-G values.
				// g values are global, so they by definition survive this.

				if(!GetData()->s_flags[0].empty()) {
					std::map<std::string, int>::iterator item = GetData()->s_flags[0].begin();
					while(item != GetData()->s_flags[0].end()) {
						if(item->first.c_str()[0] != 'g')
							GetData()->s_flags[0].erase(item++);
						else
							item++;
					}
				}
				return;
			}

			GetData()->s_flags[0][std::string(var)] = 0;
		}
	}
}
<commit_msg>And it's an extension technically, so added a vndc_enabled check<commit_after>#include "Zero.hpp"

#include "Funcs.hpp"

/*
 * Implements gsetvar vnds function.
 * gsetvar var mod val
 * Modifier is '=' '+' or '-' in script, simplify to ('-':-1, '=':0, '+':1).
 * MAY need to be UTF8 friendly
 */

void op_setvar(char* var, int* modifier, char* value) {
	if (GetData()->if_fail != 0)
		return;

	int value_r = 0, ret;
	if(value == NULL)
		ret = 0;
	else
		ret = sscanf(value, "%d", &value_r);

	if(ret == 0 && GetData()->vndc_enabled) { // value is a variable not a number
		if(*modifier == 0) {
			GetData()->s_flags[0][std::string(var)] = GetData()->s_flags[0][std::string(value)];
		}
		else if (*modifier == -1) {
			GetData()->s_flags[0][std::string(var)] -= GetData()->s_flags[0][std::string(value)];
		}
		else if (*modifier == 1) {
			GetData()->s_flags[0][std::string(var)] += GetData()->s_flags[0][std::string(value)];
		}
	}
	else {
		if(*modifier == 0) {
			GetData()->s_flags[0][std::string(var)] = value_r;
		}
		else if (*modifier == -1) {
			GetData()->s_flags[0][std::string(var)] -= value_r;
		}
		else if (*modifier == 1) {
			GetData()->s_flags[0][std::string(var)] += value_r;
		}
		else if (*modifier == -2) {
			// There's a rare case on program start where a resetall
			// happens.

			if(!strcmp(var, "~")) {
				// We'll handle it by searching through and deleting all non-G values.
				// g values are global, so they by definition survive this.

				if(!GetData()->s_flags[0].empty()) {
					std::map<std::string, int>::iterator item = GetData()->s_flags[0].begin();
					while(item != GetData()->s_flags[0].end()) {
						if(item->first.c_str()[0] != 'g')
							GetData()->s_flags[0].erase(item++);
						else
							item++;
					}
				}
				return;
			}

			GetData()->s_flags[0][std::string(var)] = 0;
		}
	}
}
<|endoftext|>


<commit_before>#include "pocketcalculator.h"
#include "calc.h"
#include "sevensegment.h"
#include <iostream>
#include <string>
#include <stdexcept>
#include <cstdlib>

namespace pocketcalculator {
	void calc(std::istream& input, std::ostream& output, unsigned const scale_factor)
	try {
		auto const result = ::calc(input);
		sevensegment::printLargeNumber(result, output, scale_factor);
	} catch(std::exception const&) {
		sevensegment::printLargeError(output, scale_factor);
	}

	unsigned automatic_scale() {
		// NOTE: can't use std::unique_ptr because the memory pointed to by the
		// pointer is not ours
		char const * const scale_ptr { std::getenv("POCKETCALCULATOR_SCALE") };

		if (scale_ptr != nullptr)
			return std::stoul(std::string { scale_ptr });

		return default_scale_factor;
	}

	void start(std::istream& input, std::ostream& output, unsigned scale_factor) {
		if (scale_factor == 0)
			scale_factor = automatic_scale();

		while (!input.eof()) calc(input, output, scale_factor);
	}
}
<commit_msg>style<commit_after>#include "pocketcalculator.h"
#include "calc.h"
#include "sevensegment.h"
#include <iostream>
#include <string>
#include <stdexcept>
#include <cstdlib>

namespace pocketcalculator {
	void calc(std::istream& input, std::ostream& output, unsigned const scale_factor)
	try {
		auto const result = ::calc(input);
		sevensegment::printLargeNumber(result, output, scale_factor);
	} catch(std::exception const&) {
		sevensegment::printLargeError(output, scale_factor);
	}

	unsigned automatic_scale() {
		// NOTE: can't use std::unique_ptr because the memory pointed to by the
		// pointer is not ours
		char const * const scale_ptr { std::getenv("POCKETCALCULATOR_SCALE") };

		if (scale_ptr != nullptr)
			return std::stoul(std::string { scale_ptr });

		return default_scale_factor;
	}

	void start(std::istream& input, std::ostream& output, unsigned scale_factor) {
		if (scale_factor == 0)
			scale_factor = automatic_scale();

		while (!input.eof())
			calc(input, output, scale_factor);
	}
}
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/lattice/behavior_decider/signal_light_scenario.h"

#include <limits>
#include <string>
#include <vector>

#include "gflags/gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/util/map_util.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/proto/planning_internal.pb.h"

namespace apollo {
namespace planning {

using apollo::common::adapter::AdapterManager;
using apollo::perception::TrafficLight;
using apollo::perception::TrafficLightDetection;
using apollo::common::util::WithinBound;

void SignalLightScenario::Reset() {}

bool SignalLightScenario::Init() {
  exist_ = true;
  return exist_;
}

int SignalLightScenario::ComputeScenarioDecision(
    Frame* frame, ReferenceLineInfo* const reference_line_info,
    PlanningTarget* planning_target) {
  CHECK(frame != nullptr);

  if (!FindValidSignalLight(reference_line_info)) {
    AINFO << "No valid signal light along reference line";
    return 0;
  }
  ReadSignals();

  for (const hdmap::PathOverlap* signal_light :
       signal_lights_along_reference_line_) {
    const TrafficLight signal = GetSignal(signal_light->object_id);
    double stop_deceleration =
        GetStopDeceleration(reference_line_info, signal_light);

    if ((signal.color() == TrafficLight::RED &&
         stop_deceleration < FLAGS_stop_max_deceleration) ||
        (signal.color() == TrafficLight::UNKNOWN &&
         stop_deceleration < FLAGS_stop_max_deceleration) ||
        (signal.color() == TrafficLight::YELLOW &&
         stop_deceleration < FLAGS_max_deacceleration_for_yellow_light_stop)) {
      CreateStopObstacle(frame, reference_line_info, signal_light);
    }
  }

  return 0;
}

bool SignalLightScenario::FindValidSignalLight(
    ReferenceLineInfo* const reference_line_info) {
  const std::vector<hdmap::PathOverlap>& signal_lights =
      reference_line_info->reference_line().map_path().signal_overlaps();
  if (signal_lights.size() <= 0) {
    ADEBUG << "No signal lights from reference line.";
    return false;
  } else {
    AINFO << "Found signal_lights size=" << signal_lights.size();
  }
  signal_lights_along_reference_line_.clear();
  for (const hdmap::PathOverlap& signal_light : signal_lights) {
    if (signal_light.start_s + FLAGS_stop_max_distance_buffer >
        reference_line_info->AdcSlBoundary().end_s()) {
      signal_lights_along_reference_line_.push_back(&signal_light);
    }
  }
  return signal_lights_along_reference_line_.size() > 0;
}

void SignalLightScenario::ReadSignals() {
  detected_signals_.clear();
  detected_signals_.clear();
  if (AdapterManager::GetTrafficLightDetection()->Empty()) {
    return;
  }
  if (AdapterManager::GetTrafficLightDetection()->GetDelaySec() >
      FLAGS_signal_expire_time_sec) {
    AWARN << "traffic signals msg is expired: "
          << AdapterManager::GetTrafficLightDetection()->GetDelaySec();
    return;
  }
  const TrafficLightDetection& detection =
      AdapterManager::GetTrafficLightDetection()->GetLatestObserved();
  for (int j = 0; j < detection.traffic_light_size(); j++) {
    const TrafficLight& signal = detection.traffic_light(j);
    detected_signals_[signal.id()] = &signal;
  }
}

TrafficLight SignalLightScenario::GetSignal(const std::string& signal_id) {
  const auto* result =
      apollo::common::util::FindPtrOrNull(detected_signals_, signal_id);
  if (result == nullptr) {
    TrafficLight traffic_light;
    traffic_light.set_id(signal_id);
    traffic_light.set_color(TrafficLight::UNKNOWN);
    traffic_light.set_confidence(0.0);
    traffic_light.set_tracking_time(0.0);
    return traffic_light;
  }
  return *result;
}

double SignalLightScenario::GetStopDeceleration(
    ReferenceLineInfo* const reference_line_info,
    const hdmap::PathOverlap* signal_light) {
  double adc_speed =
      common::VehicleStateProvider::instance()->linear_velocity();
  if (adc_speed < FLAGS_stop_min_speed) {
    return 0.0;
  }
  double stop_distance = 0.0;
  double adc_front_s = reference_line_info->AdcSlBoundary().end_s();
  double stop_line_s = signal_light->start_s;

  if (stop_line_s > adc_front_s) {
    stop_distance = stop_line_s - adc_front_s;
  } else {
    stop_distance = stop_line_s + FLAGS_stop_max_distance_buffer - adc_front_s;
  }
  if (stop_distance < 1e-5) {
    // longitudinal_acceleration_lower_bound is a negative value.
    return -FLAGS_longitudinal_acceleration_lower_bound;
  }
  return (adc_speed * adc_speed) / (2 * stop_distance);
}

void SignalLightScenario::CreateStopObstacle(
    Frame* frame, ReferenceLineInfo* const reference_line_info,
    const hdmap::PathOverlap* signal_light) {
  const auto& reference_line = reference_line_info->reference_line();
  const double stop_s =
      signal_light->start_s - FLAGS_stop_distance_traffic_light;
  const double box_center_s =
      signal_light->start_s + FLAGS_virtual_stop_wall_length / 2.0;
  if (!WithinBound(0.0, reference_line.Length(), stop_s) ||
      !WithinBound(0.0, reference_line.Length(), box_center_s)) {
    ADEBUG << "signal " << signal_light->object_id
           << " is not on reference line";
    return;
  }
  // double heading = reference_line.GetReferencePoint(stop_s).heading();
  double left_lane_width = 0.0;
  double right_lane_width = 0.0;
  reference_line.GetLaneWidth(signal_light->start_s, &left_lane_width,
                              &right_lane_width);

  /*
  auto box_center = reference_line.GetReferencePoint(box_center_s);
  common::math::Box2d stop_box{box_center, heading,
                               FLAGS_virtual_stop_wall_length,
                               left_lane_width + right_lane_width};
  PathObstacle* stop_wall =
      reference_line_info->AddObstacle(frame->AddStaticVirtualObstacle(
          FLAGS_signal_light_virtual_object_id_prefix + signal_light->object_id,
          stop_box));
  */
}

}  // namespace planning
}  // namespace apollo
<commit_msg>Planning: [lattice] recover stop fence for red traffic light<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/lattice/behavior_decider/signal_light_scenario.h"

#include <limits>
#include <string>
#include <vector>

#include "gflags/gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/util/map_util.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/proto/planning_internal.pb.h"

namespace apollo {
namespace planning {

using apollo::common::adapter::AdapterManager;
using apollo::perception::TrafficLight;
using apollo::perception::TrafficLightDetection;
using apollo::common::util::WithinBound;

void SignalLightScenario::Reset() {}

bool SignalLightScenario::Init() {
  exist_ = true;
  return exist_;
}

int SignalLightScenario::ComputeScenarioDecision(
    Frame* frame, ReferenceLineInfo* const reference_line_info,
    PlanningTarget* planning_target) {
  CHECK(frame != nullptr);

  if (!FindValidSignalLight(reference_line_info)) {
    AINFO << "No valid signal light along reference line";
    return 0;
  }
  ReadSignals();

  for (const hdmap::PathOverlap* signal_light :
       signal_lights_along_reference_line_) {
    const TrafficLight signal = GetSignal(signal_light->object_id);
    double stop_deceleration =
        GetStopDeceleration(reference_line_info, signal_light);

    if ((signal.color() == TrafficLight::RED &&
         stop_deceleration < FLAGS_stop_max_deceleration) ||
        (signal.color() == TrafficLight::UNKNOWN &&
         stop_deceleration < FLAGS_stop_max_deceleration) ||
        (signal.color() == TrafficLight::YELLOW &&
         stop_deceleration < FLAGS_max_deacceleration_for_yellow_light_stop)) {
      CreateStopObstacle(frame, reference_line_info, signal_light);
    }
  }

  return 0;
}

bool SignalLightScenario::FindValidSignalLight(
    ReferenceLineInfo* const reference_line_info) {
  const std::vector<hdmap::PathOverlap>& signal_lights =
      reference_line_info->reference_line().map_path().signal_overlaps();
  if (signal_lights.size() <= 0) {
    ADEBUG << "No signal lights from reference line.";
    return false;
  } else {
    AINFO << "Found signal_lights size=" << signal_lights.size();
  }
  signal_lights_along_reference_line_.clear();
  for (const hdmap::PathOverlap& signal_light : signal_lights) {
    if (signal_light.start_s + FLAGS_stop_max_distance_buffer >
        reference_line_info->AdcSlBoundary().end_s()) {
      signal_lights_along_reference_line_.push_back(&signal_light);
    }
  }
  return signal_lights_along_reference_line_.size() > 0;
}

void SignalLightScenario::ReadSignals() {
  detected_signals_.clear();
  detected_signals_.clear();
  if (AdapterManager::GetTrafficLightDetection()->Empty()) {
    return;
  }
  if (AdapterManager::GetTrafficLightDetection()->GetDelaySec() >
      FLAGS_signal_expire_time_sec) {
    AWARN << "traffic signals msg is expired: "
          << AdapterManager::GetTrafficLightDetection()->GetDelaySec();
    return;
  }
  const TrafficLightDetection& detection =
      AdapterManager::GetTrafficLightDetection()->GetLatestObserved();
  for (int j = 0; j < detection.traffic_light_size(); j++) {
    const TrafficLight& signal = detection.traffic_light(j);
    detected_signals_[signal.id()] = &signal;
  }
}

TrafficLight SignalLightScenario::GetSignal(const std::string& signal_id) {
  const auto* result =
      apollo::common::util::FindPtrOrNull(detected_signals_, signal_id);
  if (result == nullptr) {
    TrafficLight traffic_light;
    traffic_light.set_id(signal_id);
    traffic_light.set_color(TrafficLight::UNKNOWN);
    traffic_light.set_confidence(0.0);
    traffic_light.set_tracking_time(0.0);
    return traffic_light;
  }
  return *result;
}

double SignalLightScenario::GetStopDeceleration(
    ReferenceLineInfo* const reference_line_info,
    const hdmap::PathOverlap* signal_light) {
  double adc_speed =
      common::VehicleStateProvider::instance()->linear_velocity();
  if (adc_speed < FLAGS_stop_min_speed) {
    return 0.0;
  }
  double stop_distance = 0.0;
  double adc_front_s = reference_line_info->AdcSlBoundary().end_s();
  double stop_line_s = signal_light->start_s;

  if (stop_line_s > adc_front_s) {
    stop_distance = stop_line_s - adc_front_s;
  } else {
    stop_distance = stop_line_s + FLAGS_stop_max_distance_buffer - adc_front_s;
  }
  if (stop_distance < 1e-5) {
    // longitudinal_acceleration_lower_bound is a negative value.
    return -FLAGS_longitudinal_acceleration_lower_bound;
  }
  return (adc_speed * adc_speed) / (2 * stop_distance);
}

void SignalLightScenario::CreateStopObstacle(
    Frame* frame, ReferenceLineInfo* const reference_line_info,
    const hdmap::PathOverlap* signal_light) {
  const auto& reference_line = reference_line_info->reference_line();
  const double stop_s =
      signal_light->start_s - FLAGS_stop_distance_traffic_light;
  const double box_center_s =
      signal_light->start_s + FLAGS_virtual_stop_wall_length / 2.0;
  if (!WithinBound(0.0, reference_line.Length(), stop_s) ||
      !WithinBound(0.0, reference_line.Length(), box_center_s)) {
    ADEBUG << "signal " << signal_light->object_id
           << " is not on reference line";
    return;
  }
  double heading = reference_line.GetReferencePoint(stop_s).heading();
  double left_lane_width = 0.0;
  double right_lane_width = 0.0;
  reference_line.GetLaneWidth(signal_light->start_s, &left_lane_width,
                              &right_lane_width);

  auto box_center = reference_line.GetReferencePoint(box_center_s);
  common::math::Box2d stop_box{box_center, heading,
                               FLAGS_virtual_stop_wall_length,
                               left_lane_width + right_lane_width};
  reference_line_info->AddObstacle(frame->AddStaticVirtualObstacle(
      FLAGS_signal_light_virtual_object_id_prefix + signal_light->object_id,
      stop_box));
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>// Original class author: A.M. Jokisaari, O. Heinonen

#include "SimpleEigenStrainMaterial.h"

template<>
InputParameters validParams<SimpleEigenStrainMaterial>()
{
  InputParameters params = validParams<EigenStrainBaseMaterial>();
  params.addRequiredParam<Real>("epsilon0", "Initial eigen strain value");
  params.addParam<Real>("c0", 0.0, "Initial concentration value");
  params.addRequiredCoupledVar("c", "Concentration");
  return params;
}

SimpleEigenStrainMaterial::SimpleEigenStrainMaterial(const std::string & name,
                                                     InputParameters parameters) :
    EigenStrainBaseMaterial(name, parameters),
    _epsilon0(getParam<Real>("epsilon0")),
    _c0(getParam<Real>("c0"))
{
}

void SimpleEigenStrainMaterial::computeEigenStrain()
{
  _eigenstrain[_qp].zero();
  _eigenstrain[_qp].addIa(_epsilon0 * (_c[_qp] - _c0));

  // first derivative w.r.t. c
  _deigenstrain_dc[_qp].zero();
  _deigenstrain_dc[_qp].addIa(_epsilon0);

  // second derivative w.r.t. c (vanishes)
  _d2eigenstrain_dc2[_qp].zero();
}

void SimpleEigenStrainMaterial::computeQpElasticityTensor()
{
  _Jacobian_mult[_qp] = _elasticity_tensor[_qp] = _Cijkl;

  // the elasticity tensor is independent of c
  _delasticity_tensor_dc[_qp].zero();
  _d2elasticity_tensor_dc2[_qp].zero();
}
<commit_msg>Fix derivative (#4501)<commit_after>// Original class author: A.M. Jokisaari, O. Heinonen

#include "SimpleEigenStrainMaterial.h"

template<>
InputParameters validParams<SimpleEigenStrainMaterial>()
{
  InputParameters params = validParams<EigenStrainBaseMaterial>();
  params.addRequiredParam<Real>("epsilon0", "Initial eigen strain value");
  params.addParam<Real>("c0", 0.0, "Initial concentration value");
  params.addRequiredCoupledVar("c", "Concentration");
  return params;
}

SimpleEigenStrainMaterial::SimpleEigenStrainMaterial(const std::string & name,
                                                     InputParameters parameters) :
    EigenStrainBaseMaterial(name, parameters),
    _epsilon0(getParam<Real>("epsilon0")),
    _c0(getParam<Real>("c0"))
{
}

void SimpleEigenStrainMaterial::computeEigenStrain()
{
  _eigenstrain[_qp].zero();
  _eigenstrain[_qp].addIa(_epsilon0 * (_c[_qp] - _c0));

  // first derivative w.r.t. c
  _deigenstrain_dc[_qp].zero();
  _deigenstrain_dc[_qp].addIa(-_epsilon0); // actually delastic_strain/dc

  // second derivative w.r.t. c (vanishes)
  _d2eigenstrain_dc2[_qp].zero();
}

void SimpleEigenStrainMaterial::computeQpElasticityTensor()
{
  _Jacobian_mult[_qp] = _elasticity_tensor[_qp] = _Cijkl;

  // the elasticity tensor is independent of c
  _delasticity_tensor_dc[_qp].zero();
  _d2elasticity_tensor_dc2[_qp].zero();
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include "datapool.h"

using namespace ys;

int main() {
    dataPool<unsigned int> intpool(10, 1000);
    //intpool.push_back(1);
    //intpool.push_back(2);
    //intpool.push_back(3);
    //intpool.push_back(4);
    //intpool.push_back(5);
    //intpool.push_back(6);
    //intpool.push_back(7);

    unsigned int arr[] = {5, 322, 445,23,664,23576,443,84,37, 1};

    intpool.push_back(arr, sizeof(arr)/sizeof(int));

    for (int i = 0; i < intpool.getCurLen(); ++i) {
        printf ("%u\n", intpool[i]);
    }

    for (int i = 0; i < 10000000; ++i) {
        intpool.push_back(i);
    }
    printf ("size = %d\n", intpool.getCurLen());

    for (int i = 0; i < intpool.getCurLen(); ++i) {
        printf ("%u\n", intpool[i]);
    }

    return 0;
}

<commit_msg>Delete datapool.cpp<commit_after><|endoftext|>


<commit_before>#include "main.h"
#include <SD.h>
#include <EEPROM.h>
#include <stdio.h>

File dataFile;
uint32_t last_tick;
char filename[16];

void initLogger() {
	if (!SD.begin(10)) {
	    Serial.println("Card failed, or not present");
	    // don't do anything more:
	    return;
	}
	Serial.println("card initialized.");

	bLog = true;
	digitalWrite(LED, bLog);
	if (bLog)
		startLog();
	else
		stopLog();
}

void printDouble( double val, byte precision){
	// http://forum.arduino.cc/index.php/topic,44216.0.html#11
 // prints val with number of decimal places determine by precision
 // precision is a number from 0 to 6 indicating the desired decimial places
 // example: printDouble( 3.1415, 2); // prints 3.14 (two decimal places)

 Serial.print (int(val));  //prints the int part
 if( precision > 0) {
   Serial.print("."); // print the decimal point
   unsigned long frac;
   unsigned long mult = 1;
   byte padding = precision -1;
   while(precision--)
      mult *=10;

   if(val >= 0)
     frac = (val - int(val)) * mult;
   else
     frac = (int(val)- val ) * mult;
   unsigned long frac1 = frac;
   while( frac1 /= 10 )
     padding--;
   while(  padding--)
     Serial.print("0");
   Serial.print(frac,DEC) ;
 }
}

void cmdAcquire(char *cmd) {
	int N, n, i, v;
	int static cnt = 0;

	N = cmd[1]-'0';
	for(n=i=v=0; n<N; n++) {
		i += analogRead(4);
		v += analogRead(5);
	}
	char str[32];
//	sprintf(str, "%d: I= %d, V= %d", cnt, i/N, v/N);
	sprintf(str, "%5d: I= %4d (%02.2fA)", cnt/10.0, i/N, (A6-511)*30.0/512);
	sendMsg(str);

	if (bLog) {
		pinMode(2, OUTPUT);
		digitalWrite(2, LOW);
		pinMode(3, OUTPUT);
		digitalWrite(3, LOW);

		digitalWrite(2, HIGH);
		if ((cnt % 10) == 0)
			dataFile = SD.open(filename, FILE_WRITE);
		if (dataFile) {
			digitalWrite(3, HIGH);
			dataFile.println(str);
			digitalWrite(3, LOW);
			if ((cnt % 10) == 9)
				dataFile.close();
			digitalWrite(2, LOW);
		}
		else
			Serial.println("error opening datalog.txt");
		cnt++;
	}
}

void startLog() {

	int nFile = (EEPROM.read(0) << 8) + EEPROM.read(1);
	sprintf(filename, "file%04d.txt", nFile);
	Serial.println(filename);
	nFile++;
	EEPROM.write(0, nFile >> 8);
	EEPROM.write(1, nFile & 0xFF);
}

#define PERIOD 100

void tickLog() {
	uint32_t t = millis();
	if (t > last_tick + PERIOD) {
		last_tick += PERIOD;
		cmdAcquire("a1");
	}
}

void stopLog() {
}
<commit_msg>Dados em csv<commit_after>#include "main.h"
#include <SD.h>
#include <EEPROM.h>
#include <stdio.h>

File dataFile;
uint32_t last_tick;
int sample;

void initLogger() {
	if (!SD.begin(10)) {
	    Serial.println("Card failed, or not present");
	    // don't do anything more:
	    return;
	}
	Serial.println("card initialized.");

	bLog = true;
	digitalWrite(LED, bLog);
	if (bLog)
		startLog();
	else
		stopLog();
}

void cmdAcquire(char *cmd) {
	int N, n, i, v;

	N = cmd[1]-'0';
	for(n=i=v=0; n<N; n++) {
		i += analogRead(4);
	}
//	char fstr[32], str[32];
//	dtostrf((i/N-511)/13.2, 5, 2, fstr);
	char str[32];
	sprintf(str, "%5d,%4d", sample, i/N);
	sendMsg(str);

	if (bLog) {
		if (dataFile) {
			dataFile.println(str);
			if ((sample % 10) == 0)
				dataFile.flush();
		}
		else
			Serial.println("error opening datalog.txt");
		sample++;
	}
}

#define PERIOD 100

void startLog() {
	char filename[16];

	last_tick = millis() - PERIOD;
	sample = 1;

	// set filename
	int nFile = (EEPROM.read(0) << 8) + EEPROM.read(1);
	sprintf(filename, "file%04d.csv", nFile);
	nFile++;
	EEPROM.write(0, nFile >> 8);
	EEPROM.write(1, nFile & 0xFF);

	Serial.println(filename);
	dataFile = SD.open(filename, FILE_WRITE);
	dataFile.println("t(1/10s),I(0..1023)");

}

void tickLog() {
	uint32_t t = millis();
	if (t > last_tick + PERIOD) {
		last_tick += PERIOD;
		cmdAcquire("a4");
	}
}

void stopLog() {
	dataFile.close();
	sample = 0;
}
<|endoftext|>


<commit_before>#include <debugger/impl.h>
#include <debugger/io/base.h>
#include <debugger/capabilities.h>
#include <debugger/luathread.h>

namespace vscode
{
	void debugger_impl::response_initialize(rprotocol& req)
	{
		if (req.HasMember("__norepl") && req["__norepl"].IsBool() && req["__norepl"].GetBool())
		{
			seq++;
			return;
		}
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("response");
			res("seq").Int64(1);
			res("command").String("initialize");
			res("request_seq").Int64(req["seq"].GetInt64());
			res("success").Bool(true);
			capabilities(res);
		}
		io_output(res);
	}

	void debugger_impl::response_thread(rprotocol& req)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("response");
			res("seq").Int64(seq++);
			res("command").String(req["command"]);
			res("request_seq").Int64(req["seq"].GetInt64());
			res("success").Bool(true);
			for (auto _ : res("body").Object())
			{
				for (auto _ : res("threads").Array())
				{
					for (auto _ : res.Object())
					{
						res("name").String("LuaThread");
						res("id").Int(1);
					}
				}
			}
		}
		io_output(res);
	}

	void debugger_impl::response_source(rprotocol& req, const char* content)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("response");
			res("seq").Int64(seq++);
			res("command").String(req["command"]);
			res("request_seq").Int64(req["seq"].GetInt64());
			res("success").Bool(true);
			for (auto _ : res("body").Object())
			{
				res("content").String(content);
				res("mimeType").String("text/x-lua");
			}
		}
		io_output(res);
	}

	void debugger_impl::event_stopped(luathread* thread, const char *msg)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("event");
			res("seq").Int64(seq++);
			res("event").String("stopped");
			for (auto _ : res("body").Object())
			{
				res("reason").String(msg);
				res("threadId").Int(thread->id);
			}
		}
		io_output(res);
	}

	void debugger_impl::event_thread(luathread* thread, bool started)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("event");
			res("seq").Int64(seq++);
			res("event").String("thread");
			for (auto _ : res("body").Object())
			{
				res("reason").String(started ? "started" : "exited");
				res("threadId").Int(thread->id);
			}
		}
		io_output(res);
	}

	void debugger_impl::event_terminated()
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("event");
			res("seq").Int64(seq++);
			res("event").String("terminated");
			for (auto _ : res("body").Object())
			{
				res("restart").Bool(false);
			}
		}
		io_output(res);
	}

	void debugger_impl::event_initialized()
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("event");
			res("seq").Int64(seq++);
			res("event").String("initialized");
		}
		io_output(res);
	}

	void debugger_impl::event_capabilities()
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("event");
			res("seq").Int64(seq++);
			res("event").String("capabilities");
			capabilities(res);
		}
		io_output(res);
	}
	void debugger_impl::response_error(rprotocol& req, const char *msg)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("response");
			res("seq").Int64(seq++);
			res("command").String(req["command"]);
			res("request_seq").Int64(req["seq"].GetInt64());
			res("success").Bool(false);
			res("message").String(msg);
		}
		io_output(res);
	}

	void debugger_impl::response_success(rprotocol& req)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("response");
			res("seq").Int64(seq++);
			res("command").String(req["command"]);
			res("request_seq").Int64(req["seq"].GetInt64());
			res("success").Bool(true);
		}
		io_output(res);
	}

	void debugger_impl::response_success(rprotocol& req, std::function<void(wprotocol&)> body)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("response");
			res("seq").Int64(seq++);
			res("command").String(req["command"]);
			res("request_seq").Int64(req["seq"].GetInt64());
			res("success").Bool(true);
			for (auto _ : res("body").Object())
			{
				body(res);
			}
		}
		io_output(res);
	}
}
<commit_msg>修正线程列表不对的问题<commit_after>#include <debugger/impl.h>
#include <debugger/io/base.h>
#include <debugger/capabilities.h>
#include <debugger/luathread.h>

namespace vscode
{
	void debugger_impl::response_initialize(rprotocol& req)
	{
		if (req.HasMember("__norepl") && req["__norepl"].IsBool() && req["__norepl"].GetBool())
		{
			seq++;
			return;
		}
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("response");
			res("seq").Int64(1);
			res("command").String("initialize");
			res("request_seq").Int64(req["seq"].GetInt64());
			res("success").Bool(true);
			capabilities(res);
		}
		io_output(res);
	}

	void debugger_impl::response_thread(rprotocol& req)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("response");
			res("seq").Int64(seq++);
			res("command").String(req["command"]);
			res("request_seq").Int64(req["seq"].GetInt64());
			res("success").Bool(true);
			for (auto _ : res("body").Object())
			{
				for (auto _ : res("threads").Array())
				{
					for (auto& lt : luathreads_)
					{
						for (auto _ : res.Object())
						{
							res("name").String("LuaThread");
							res("id").Int(lt.second->id);
						}
					}
				}
			}
		}
		io_output(res);
	}

	void debugger_impl::response_source(rprotocol& req, const char* content)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("response");
			res("seq").Int64(seq++);
			res("command").String(req["command"]);
			res("request_seq").Int64(req["seq"].GetInt64());
			res("success").Bool(true);
			for (auto _ : res("body").Object())
			{
				res("content").String(content);
				res("mimeType").String("text/x-lua");
			}
		}
		io_output(res);
	}

	void debugger_impl::event_stopped(luathread* thread, const char *msg)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("event");
			res("seq").Int64(seq++);
			res("event").String("stopped");
			for (auto _ : res("body").Object())
			{
				res("reason").String(msg);
				res("threadId").Int(thread->id);
			}
		}
		io_output(res);
	}

	void debugger_impl::event_thread(luathread* thread, bool started)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("event");
			res("seq").Int64(seq++);
			res("event").String("thread");
			for (auto _ : res("body").Object())
			{
				res("reason").String(started ? "started" : "exited");
				res("threadId").Int(thread->id);
			}
		}
		io_output(res);
	}

	void debugger_impl::event_terminated()
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("event");
			res("seq").Int64(seq++);
			res("event").String("terminated");
			for (auto _ : res("body").Object())
			{
				res("restart").Bool(false);
			}
		}
		io_output(res);
	}

	void debugger_impl::event_initialized()
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("event");
			res("seq").Int64(seq++);
			res("event").String("initialized");
		}
		io_output(res);
	}

	void debugger_impl::event_capabilities()
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("event");
			res("seq").Int64(seq++);
			res("event").String("capabilities");
			capabilities(res);
		}
		io_output(res);
	}
	void debugger_impl::response_error(rprotocol& req, const char *msg)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("response");
			res("seq").Int64(seq++);
			res("command").String(req["command"]);
			res("request_seq").Int64(req["seq"].GetInt64());
			res("success").Bool(false);
			res("message").String(msg);
		}
		io_output(res);
	}

	void debugger_impl::response_success(rprotocol& req)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("response");
			res("seq").Int64(seq++);
			res("command").String(req["command"]);
			res("request_seq").Int64(req["seq"].GetInt64());
			res("success").Bool(true);
		}
		io_output(res);
	}

	void debugger_impl::response_success(rprotocol& req, std::function<void(wprotocol&)> body)
	{
		wprotocol res;
		for (auto _ : res.Object())
		{
			res("type").String("response");
			res("seq").Int64(seq++);
			res("command").String(req["command"]);
			res("request_seq").Int64(req["seq"].GetInt64());
			res("success").Bool(true);
			for (auto _ : res("body").Object())
			{
				body(res);
			}
		}
		io_output(res);
	}
}
<|endoftext|>


<commit_before>//===-- examples/clang-interpreter/main.cpp - Clang C Interpreter Example -===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/CodeGenAction.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/DiagnosticOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"

#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Config/config.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Host.h"
#include "llvm/System/Path.h"
#include "llvm/Target/TargetSelect.h"
using namespace clang;
using namespace clang::driver;

llvm::sys::Path GetExecutablePath(const char *Argv0) {
  // This just needs to be some symbol in the binary; C++ doesn't
  // allow taking the address of ::main however.
  void *MainAddr = (void*) (intptr_t) GetExecutablePath;
  return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);
}

int Execute(llvm::Module *Mod, char * const *envp) {
  llvm::InitializeNativeTarget();

  std::string Error;
  llvm::OwningPtr<llvm::ExecutionEngine> EE(
    llvm::ExecutionEngine::createJIT(Mod, &Error));
  if (!EE) {
    llvm::errs() << "unable to make execution engine: " << Error << "\n";
    return 255;
  }

  llvm::Function *EntryFn = Mod->getFunction("main");
  if (!EntryFn) {
    llvm::errs() << "'main' function not found in module.\n";
    return 255;
  }

  // FIXME: Support passing arguments.
  std::vector<std::string> Args;
  Args.push_back(Mod->getModuleIdentifier());

  return EE->runFunctionAsMain(EntryFn, Args, envp);
}

int main(int argc, const char **argv, char * const *envp) {
  void *MainAddr = (void*) (intptr_t) GetExecutablePath;
  llvm::sys::Path Path = GetExecutablePath(argv[0]);
  TextDiagnosticPrinter DiagClient(llvm::errs(), DiagnosticOptions());

  Diagnostic Diags(&DiagClient);
  Driver TheDriver(Path.getBasename(), Path.getDirname(),
                   llvm::sys::getHostTriple(),
                   "a.out", /*IsProduction=*/false, /*CXXIsProduction=*/false,
                   Diags);
  TheDriver.setTitle("clang interpreter");

  // FIXME: This is a hack to try to force the driver to do something we can
  // recognize. We need to extend the driver library to support this use model
  // (basically, exactly one input, and the operation mode is hard wired).
  llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
  Args.push_back("-fsyntax-only");
  llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(),
                                                            Args.data()));
  if (!C)
    return 0;

  // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.

  // We expect to get back exactly one command job, if we didn't something
  // failed. Extract that job from the compilation.
  const driver::JobList &Jobs = C->getJobs();
  if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
    llvm::SmallString<256> Msg;
    llvm::raw_svector_ostream OS(Msg);
    C->PrintJob(OS, C->getJobs(), "; ", true);
    Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
    return 1;
  }

  const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
  if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
    Diags.Report(diag::err_fe_expected_clang_command);
    return 1;
  }

  // Initialize a compiler invocation object from the clang (-cc1) arguments.
  const driver::ArgStringList &CCArgs = Cmd->getArguments();
  llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
  CompilerInvocation::CreateFromArgs(*CI, (const char**) CCArgs.data(),
                                     (const char**) CCArgs.data()+CCArgs.size(),
                                     Diags);

  // Show the invocation, with -v.
  if (CI->getHeaderSearchOpts().Verbose) {
    llvm::errs() << "clang invocation:\n";
    C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
    llvm::errs() << "\n";
  }

  // FIXME: This is copied from cc1_main.cpp; simplify and eliminate.

  // Create a compiler instance to handle the actual work.
  CompilerInstance Clang;
  Clang.setLLVMContext(new llvm::LLVMContext);
  Clang.setInvocation(CI.take());

  // Create the compilers actual diagnostics engine.
  Clang.createDiagnostics(int(CCArgs.size()), (char**) CCArgs.data());
  if (!Clang.hasDiagnostics())
    return 1;

  // Infer the builtin include path if unspecified.
  if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
      Clang.getHeaderSearchOpts().ResourceDir.empty())
    Clang.getHeaderSearchOpts().ResourceDir =
      CompilerInvocation::GetResourcesPath(argv[0], MainAddr);

  // Create and execute the frontend to generate an LLVM bitcode module.
  llvm::OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction());
  if (!Clang.ExecuteAction(*Act))
    return 1;

  int Res = 255;
  if (llvm::Module *Module = Act->takeModule())
    Res = Execute(Module, envp);

  // Shutdown.

  llvm::llvm_shutdown();

  return Res;
}
<commit_msg>Fix -Wcast-qual warnings.<commit_after>//===-- examples/clang-interpreter/main.cpp - Clang C Interpreter Example -===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/CodeGenAction.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/DiagnosticOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"

#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Config/config.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Host.h"
#include "llvm/System/Path.h"
#include "llvm/Target/TargetSelect.h"
using namespace clang;
using namespace clang::driver;

llvm::sys::Path GetExecutablePath(const char *Argv0) {
  // This just needs to be some symbol in the binary; C++ doesn't
  // allow taking the address of ::main however.
  void *MainAddr = (void*) (intptr_t) GetExecutablePath;
  return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);
}

int Execute(llvm::Module *Mod, char * const *envp) {
  llvm::InitializeNativeTarget();

  std::string Error;
  llvm::OwningPtr<llvm::ExecutionEngine> EE(
    llvm::ExecutionEngine::createJIT(Mod, &Error));
  if (!EE) {
    llvm::errs() << "unable to make execution engine: " << Error << "\n";
    return 255;
  }

  llvm::Function *EntryFn = Mod->getFunction("main");
  if (!EntryFn) {
    llvm::errs() << "'main' function not found in module.\n";
    return 255;
  }

  // FIXME: Support passing arguments.
  std::vector<std::string> Args;
  Args.push_back(Mod->getModuleIdentifier());

  return EE->runFunctionAsMain(EntryFn, Args, envp);
}

int main(int argc, const char **argv, char * const *envp) {
  void *MainAddr = (void*) (intptr_t) GetExecutablePath;
  llvm::sys::Path Path = GetExecutablePath(argv[0]);
  TextDiagnosticPrinter DiagClient(llvm::errs(), DiagnosticOptions());

  Diagnostic Diags(&DiagClient);
  Driver TheDriver(Path.getBasename(), Path.getDirname(),
                   llvm::sys::getHostTriple(),
                   "a.out", /*IsProduction=*/false, /*CXXIsProduction=*/false,
                   Diags);
  TheDriver.setTitle("clang interpreter");

  // FIXME: This is a hack to try to force the driver to do something we can
  // recognize. We need to extend the driver library to support this use model
  // (basically, exactly one input, and the operation mode is hard wired).
  llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
  Args.push_back("-fsyntax-only");
  llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(),
                                                            Args.data()));
  if (!C)
    return 0;

  // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.

  // We expect to get back exactly one command job, if we didn't something
  // failed. Extract that job from the compilation.
  const driver::JobList &Jobs = C->getJobs();
  if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
    llvm::SmallString<256> Msg;
    llvm::raw_svector_ostream OS(Msg);
    C->PrintJob(OS, C->getJobs(), "; ", true);
    Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
    return 1;
  }

  const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
  if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
    Diags.Report(diag::err_fe_expected_clang_command);
    return 1;
  }

  // Initialize a compiler invocation object from the clang (-cc1) arguments.
  const driver::ArgStringList &CCArgs = Cmd->getArguments();
  llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
  CompilerInvocation::CreateFromArgs(*CI,
                                     const_cast<const char **>(CCArgs.data()),
                                     const_cast<const char **>(CCArgs.data()) +
                                       CCArgs.size(),
                                     *Diags);

  // Show the invocation, with -v.
  if (CI->getHeaderSearchOpts().Verbose) {
    llvm::errs() << "clang invocation:\n";
    C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
    llvm::errs() << "\n";
  }

  // FIXME: This is copied from cc1_main.cpp; simplify and eliminate.

  // Create a compiler instance to handle the actual work.
  CompilerInstance Clang;
  Clang.setLLVMContext(new llvm::LLVMContext);
  Clang.setInvocation(CI.take());

  // Create the compilers actual diagnostics engine.
  Clang.createDiagnostics(int(CCArgs.size()), (char**) CCArgs.data());
  if (!Clang.hasDiagnostics())
    return 1;

  // Infer the builtin include path if unspecified.
  if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
      Clang.getHeaderSearchOpts().ResourceDir.empty())
    Clang.getHeaderSearchOpts().ResourceDir =
      CompilerInvocation::GetResourcesPath(argv[0], MainAddr);

  // Create and execute the frontend to generate an LLVM bitcode module.
  llvm::OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction());
  if (!Clang.ExecuteAction(*Act))
    return 1;

  int Res = 255;
  if (llvm::Module *Module = Act->takeModule())
    Res = Execute(Module, envp);

  // Shutdown.

  llvm::llvm_shutdown();

  return Res;
}
<|endoftext|>


<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2020 - 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

#include "iceoryx_binding_c/internal/cpp2c_enum_translation.hpp"
#include "iceoryx_binding_c/enums.h"

using namespace iox;
using namespace iox::popo;

namespace cpp2c
{
iox_SubscribeState SubscribeState(const iox::SubscribeState value)
{
    switch (value)
    {
    case iox::SubscribeState::NOT_SUBSCRIBED:
        return iox_SubscribeState::SubscribeState_NOT_SUBSCRIBED;
    case iox::SubscribeState::SUBSCRIBE_REQUESTED:
        return iox_SubscribeState::SubscribeState_SUBSCRIBE_REQUESTED;
    case iox::SubscribeState::SUBSCRIBED:
        return iox_SubscribeState::SubscribeState_SUBSCRIBED;
    case iox::SubscribeState::UNSUBSCRIBE_REQUESTED:
        return iox_SubscribeState::SubscribeState_UNSUBSCRIBE_REQUESTED;
    case iox::SubscribeState::WAIT_FOR_OFFER:
        return iox_SubscribeState::SubscribeState_WAIT_FOR_OFFER;
    default:
        return iox_SubscribeState::SubscribeState_UNDEFINED_ERROR;
    }
}

iox_ChunkReceiveResult ChunkReceiveResult(const iox::popo::ChunkReceiveResult value)
{
    switch (value)
    {
    case ChunkReceiveResult::NO_CHUNK_AVAILABLE:
        return ChunkReceiveResult_NO_CHUNK_AVAILABLE;
    case ChunkReceiveResult::TOO_MANY_CHUNKS_HELD_IN_PARALLEL:
        return ChunkReceiveResult_TOO_MANY_CHUNKS_HELD_IN_PARALLEL;
    default:
        return ChunkReceiveResult_UNDEFINED_ERROR;
    }
}

iox_AllocationResult AllocationResult(const iox::popo::AllocationError value)
{
    switch (value)
    {
    case AllocationError::RUNNING_OUT_OF_CHUNKS:
        return AllocationResult_RUNNING_OUT_OF_CHUNKS;
    case AllocationError::TOO_MANY_CHUNKS_ALLOCATED_IN_PARALLEL:
        return AllocationResult_TOO_MANY_CHUNKS_ALLOCATED_IN_PARALLEL;
    default:
        return AllocationResult_UNDEFINED_ERROR;
    }
}

iox_WaitSetResult WaitSetResult(const iox::popo::WaitSetError value)
{
    switch (value)
    {
    case WaitSetError::WAIT_SET_FULL:
        return WaitSetResult_WAIT_SET_FULL;
    case WaitSetError::EVENT_ALREADY_ATTACHED:
        return WaitSetResult_EVENT_ALREADY_ATTACHED;
    default:
        return WaitSetResult_UNDEFINED_ERROR;
    }
}

} // namespace cpp2c
<commit_msg>iox-#495 Add namespace to enum<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2020 - 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

#include "iceoryx_binding_c/internal/cpp2c_enum_translation.hpp"
#include "iceoryx_binding_c/enums.h"

using namespace iox;
using namespace iox::popo;

namespace cpp2c
{
iox_SubscribeState SubscribeState(const iox::SubscribeState value)
{
    switch (value)
    {
    case iox::SubscribeState::NOT_SUBSCRIBED:
        return iox_SubscribeState::SubscribeState_NOT_SUBSCRIBED;
    case iox::SubscribeState::SUBSCRIBE_REQUESTED:
        return iox_SubscribeState::SubscribeState_SUBSCRIBE_REQUESTED;
    case iox::SubscribeState::SUBSCRIBED:
        return iox_SubscribeState::SubscribeState_SUBSCRIBED;
    case iox::SubscribeState::UNSUBSCRIBE_REQUESTED:
        return iox_SubscribeState::SubscribeState_UNSUBSCRIBE_REQUESTED;
    case iox::SubscribeState::WAIT_FOR_OFFER:
        return iox_SubscribeState::SubscribeState_WAIT_FOR_OFFER;
    default:
        return iox_SubscribeState::SubscribeState_UNDEFINED_ERROR;
    }
}

iox_ChunkReceiveResult ChunkReceiveResult(const iox::popo::ChunkReceiveResult value)
{
    switch (value)
    {
    case iox::popo::ChunkReceiveResult::NO_CHUNK_AVAILABLE:
        return ChunkReceiveResult_NO_CHUNK_AVAILABLE;
    case iox::popo::ChunkReceiveResult::TOO_MANY_CHUNKS_HELD_IN_PARALLEL:
        return ChunkReceiveResult_TOO_MANY_CHUNKS_HELD_IN_PARALLEL;
    default:
        return ChunkReceiveResult_UNDEFINED_ERROR;
    }
}

iox_AllocationResult AllocationResult(const iox::popo::AllocationError value)
{
    switch (value)
    {
    case AllocationError::RUNNING_OUT_OF_CHUNKS:
        return AllocationResult_RUNNING_OUT_OF_CHUNKS;
    case AllocationError::TOO_MANY_CHUNKS_ALLOCATED_IN_PARALLEL:
        return AllocationResult_TOO_MANY_CHUNKS_ALLOCATED_IN_PARALLEL;
    default:
        return AllocationResult_UNDEFINED_ERROR;
    }
}

iox_WaitSetResult WaitSetResult(const iox::popo::WaitSetError value)
{
    switch (value)
    {
    case WaitSetError::WAIT_SET_FULL:
        return WaitSetResult_WAIT_SET_FULL;
    case WaitSetError::EVENT_ALREADY_ATTACHED:
        return WaitSetResult_EVENT_ALREADY_ATTACHED;
    default:
        return WaitSetResult_UNDEFINED_ERROR;
    }
}

} // namespace cpp2c
<|endoftext|>