Пример #1
0
static VALUE *docolon(VALUE *sv, VALUE *pv)
{
	enum { NMATCH = 2 };
	VALUE *v;
#if defined(__UC_LIBC__)
	regexp *re_buffer;
    int len;
#else
	regex_t re_buffer;
	regmatch_t re_regs[NMATCH];
#endif

	tostring(sv);
	tostring(pv);

	if (pv->u.s[0] == '^') {
		bb_error_msg(
"warning: '%s': using '^' as the first character\n"
"of a basic regular expression is not portable; it is ignored", pv->u.s);
	}

#if defined(__UC_LIBC__)
	re_buffer = regcomp(pv->u.s);
	if (re_buffer == NULL) {
		regerror("NULL buffer");
		exit(1);
	}
	len = regexec(re_buffer, sv->u.s);
	v = int_value(len);
	free(re_buffer);
#else
	memset(&re_buffer, 0, sizeof(re_buffer));
	memset(re_regs, 0, sizeof(re_regs));
	xregcomp(&re_buffer, pv->u.s, 0);

	/* expr uses an anchored pattern match, so check that there was a
	 * match and that the match starts at offset 0. */
	if (regexec(&re_buffer, sv->u.s, NMATCH, re_regs, 0) != REG_NOMATCH
	 && re_regs[0].rm_so == 0
	) {
		/* Were \(...\) used? */
		if (re_buffer.re_nsub > 0 && re_regs[1].rm_so >= 0) {
			sv->u.s[re_regs[1].rm_eo] = '\0';
			v = str_value(sv->u.s + re_regs[1].rm_so);
		} else {
			v = int_value(re_regs[0].rm_eo);
		}
	} else {
		/* Match failed -- return the right kind of null.  */
		if (re_buffer.re_nsub > 0)
			v = str_value("");
		else
			v = int_value(0);
	}
	regfree(&re_buffer);
#endif
	return v;
}
Пример #2
0
JSON *non_type_parse(){
    if (str_value() == ' ')
        next_non_space_char();
    if (str_value() == '"'){
        //string type
        return string_type_parse();
    }
    else if ( str_value()>='0'&& str_value()<='9'){
        //num type
        return num_type_parse();
    }
    else if ( str_value()=='{'){
        //object type
        return object_type_parse();
    }
    else if ( str_value()=='['){
        //array type
        return array_type_parse();
    }
    else if ( str_value()=='n'){
        //null type
        return null_type_parse();
    }
    else if ( str_value()=='f'){
        //false type
        return false_type_parse();
    }
    else if ( str_value()=='t'){
        return true_type_parse();
    }
    else 
        return NULL;
}
Пример #3
0
JSON *array_type_parse(){
    JSON *arr_obj = CreateArray();
    next_char();
    next_non_space_char();
    while (str_value() != ']'){
        AddItemToArray(arr_obj, non_type_parse());
        next_non_space_char();
        if (str_value()==','){
            next_char();
        }
    }
    next_char();
    return arr_obj;
}
Пример #4
0
JSON *object_type_parse(){
    JSON *obj = CreateObject();
    next_char();
    next_non_space_char();
    while (str_value() != '}'){
        JSON *ent_obj = entry_type_parse();
        AddEntryToObject(obj, ent_obj);
        next_non_space_char();
        if (str_value() == ',')
            next_char();
        next_non_space_char();
    }
    next_char();
    return obj;
}
Пример #5
0
/*
 * Find the struct objaddr for an opclass or opfamily.
 */
static struct objaddr
get_objaddr_opcf(objtype_e objtype, struct list *objname, struct list *objargs)
{
	oid_t amoid;
	struct objaddr address;

	ASSERT(list_length(objargs) == 1);
	amoid = get_am_oid(str_value(linitial(objargs)), false);

	switch (objtype) {
	case OBJECT_OPCLASS:
		address.classId = OperatorClassRelationId;
		address.objectId = get_opclass_oid(amoid, objname, false);
		address.objectSubId = 0;
		break;

	case OBJECT_OPFAMILY:
		address.classId = OperatorFamilyRelationId;
		address.objectId = get_opfamily_oid(amoid, objname, false);
		address.objectSubId = 0;
		break;

	default:
		elog(ERROR, "unrecognized objtype: %d", (int) objtype);
		/* placate compiler, which doesn't know elog won't return */
		address.classId = INVALID_OID;
		address.objectId = INVALID_OID;
		address.objectSubId = 0;
	}

	return address;
}
Пример #6
0
/*
 * Find the struct objaddr for an attribute.
 */
static struct objaddr
get_objaddr_attr(
	objtype_e objtype,
	struct list* objname,
	struct relation** relp,
	lockmode_t lockmode)
{
	struct objaddr address;
	struct list* relname;
	oid_t reloid;
	struct relation* relation;
	const char *attname;

	/* Extract relation name and open relation. */
	attname = str_value(lfirst(list_tail(objname)));
	relname = list_truncate(list_copy(objname), list_length(objname) - 1);
	relation = relation_openrv(nl_to_range_var(relname), lockmode);
	reloid = REL_ID(relation);

	/* Look up attribute and construct return value. */
	address.classId = RelationRelationId;
	address.objectId = reloid;
	address.objectSubId = get_attnum(reloid, attname);
	if (address.objectSubId == INVALID_ATTR_NR) {
		ereport(ERROR, (
		errcode(E_UNDEFINED_COLUMN),
		errmsg("column \"%s\" of relation \"%s\" does not exist",
			attname,
			REL_NAME(relation))));
	}

	*relp = relation;
	return address;
}
Пример #7
0
// Called to parse a RCSS number declaration.
bool PropertyParserNumber::ParseValue(Property& property, const String& value, const ParameterMap& ROCKET_UNUSED_PARAMETER(parameters)) const
{
	ROCKET_UNUSED(parameters);

	// Default to a simple number.
	property.unit = Property::NUMBER;

	// Check for a unit declaration at the end of the number.
	size_t unit_pos =  value.Length();
	for (size_t i = 0; i < unit_suffixes.size(); i++)
	{
		const UnitSuffix& unit_suffix = unit_suffixes[i];

		if (value.Length() < unit_suffix.second.Length())
			continue;

		size_t test_unit_pos = value.Length() - unit_suffix.second.Length();
		if (strcasecmp(value.CString() + test_unit_pos, unit_suffix.second.CString()) == 0)
		{
			unit_pos = test_unit_pos;
			property.unit = unit_suffix.first;
			break;
		}
	}

	float float_value;
	String str_value( value.CString(), value.CString() + unit_pos );
	if (sscanf(str_value.CString(), "%f", &float_value) == 1)
	{
		property.value = Variant(float_value);
		return true;
	}

	return false;
}
Пример #8
0
JSON *entry_type_parse(){
    next_non_space_char(); // get char '"'
    JSON *key_obj = string_type_parse();
    next_non_space_char();
    assert(str_value() == ':');
    next_char();
    JSON *value_obj = non_type_parse();
    return CreateEntry(key_obj->valuestring, value_obj);
}
Пример #9
0
static int
set_str(_RepoObject *self, PyObject *value, void *closure)
{
    intptr_t str_key = (intptr_t)closure;
    PycompString str_value(value);
    if (!str_value.getCString())
        return -1;
    hy_repo_set_string(self->repo, str_key, str_value.getCString());
    return 0;
}
Пример #10
0
JSON *num_type_parse(){
    double val = 0;
    int dp_found = 0;
    double div = 0;
    while ((str_value()>='0'&& str_value()<='9')|| str_value()=='.'){
        // decimal point
        if (str_value() == '.'){
            assert(dp_found==0);
            dp_found = 1;
            div = 1;
        }
        // digital
        else{
            div *= 10;
            val = val * 10 + (str_value()-'0');
        }
        next_char();
    }
    if (dp_found)
        val /= div;
    return CreateNumber(val);
}
Пример #11
0
void PythonModule::report_handler(const sc_core::sc_report &rep, const sc_core::sc_actions &actions) {
  block_threads();
  const sr_report *srr = dynamic_cast<const sr_report *>(&rep);
  PyObject *pairs = PyDict_New();
  if(srr) {
    for(std::vector<v::pair>::const_iterator iter = srr->pairs.begin(); iter!=srr->pairs.end(); iter++) {
      PyObject *i = NULL;
      switch(iter->type) {
        case v::pair::INT32:  i = PyLong_FromLong(boost::any_cast<int32_t>(iter->data)); break;
        case v::pair::UINT32: i = PyLong_FromLong(boost::any_cast<uint32_t>(iter->data)); break;
        case v::pair::INT64:  i = PyLong_FromLongLong(boost::any_cast<int64_t>(iter->data)); break;
        case v::pair::UINT64: i = PyLong_FromUnsignedLongLong(boost::any_cast<uint64_t>(iter->data)); break;
        case v::pair::STRING: i = PyString_FromString(boost::any_cast<std::string>(iter->data).c_str()); break;
        case v::pair::BOOL:   i =                   (boost::any_cast<bool>(iter->data))? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False); break;
        case v::pair::DOUBLE: i = PyFloat_FromDouble(boost::any_cast<double>(iter->data)); break;
        case v::pair::TIME:   i = PyFloat_FromDouble(boost::any_cast<sc_core::sc_time>(iter->data).to_default_time_units()); break;
        default:              i = PyLong_FromLong(boost::any_cast<int32_t>(iter->data));
      }
      if(i) {
        PyObject *key = PyUnicode_FromString(iter->name.c_str());
        PyDict_SetItem(pairs, key, i);
        Py_XDECREF(key);
        Py_XDECREF(i);
      } else {
        std::cout << "could not convert to python: " << iter->name << std::endl;
      }
    }
  }

  if(rep.get_severity()==sc_core::SC_MAX_SEVERITY && rep.get_verbosity() == 0x0FFFFFFF && std::strncmp(rep.get_msg(), "command", 8) == 0) {
    PyObject *obj = PyTuple_New(1);
    PyTuple_SetItem(obj, 0, PyString_FromString(str_value(rep.get_msg_type())));
    PythonModule::globalInstance->run_py_callback("command", obj, pairs);
    Py_XDECREF(obj);

  } else {
    PyObject *obj = PyTuple_New(11);
    PyTuple_SetItem(obj, 0, PyString_FromString(str_value(rep.get_msg_type())));
    PyTuple_SetItem(obj, 1, PyString_FromString(str_value(rep.get_msg())));
    PyTuple_SetItem(obj, 2, PyLong_FromLong(rep.get_severity()));
    PyTuple_SetItem(obj, 3, PyString_FromString(str_value(rep.get_file_name())));
    PyTuple_SetItem(obj, 4, PyLong_FromLong(rep.get_line_number()));
    PyTuple_SetItem(obj, 5, PyFloat_FromDouble(rep.get_time().to_default_time_units()));
    PyTuple_SetItem(obj, 6, PyLong_FromLong(sc_core::sc_delta_count()));
    PyTuple_SetItem(obj, 7, PyString_FromString(str_value(rep.get_process_name())));
    PyTuple_SetItem(obj, 8, PyLong_FromLong(rep.get_verbosity()));
    PyTuple_SetItem(obj, 9, PyString_FromString(str_value(rep.what())));
    PyTuple_SetItem(obj, 10, PyLong_FromLong(actions));
    PythonModule::globalInstance->run_py_callback("report", obj, pairs);
    Py_XDECREF(obj);

    //if(actions & (sc_core::SC_STOP | sc_core::SC_ABORT | sc_core::SC_INTERRUPT | sc_core::SC_THROW)) {
    //  sc_core::sc_report_handler::default_handler(rep, actions & ~(sc_core::SC_DISPLAY | sc_core::SC_LOG));
    //}
  }
  Py_XDECREF(pairs);
  unblock_threads();
}
Пример #12
0
JSON *string_type_parse(){
    char *op = str_addr();
    op++;
    next_char();
    while (str_value() != '"'){
        assert(is_end()==0);
        next_char();
    }
    set_char(0);
    JSON *obj = CreateString(op);
    set_char('"');
    next_char();
    //puts(s);
    return obj;
}
Пример #13
0
void set_cell(WINDOW *win, int i, int j, int ioff, int joff,
	      int type, int nx, void *data)
{
  char line[BUFSIZ];
  int len, k, d;
  chtype chline[BUFSIZ];
  extern int colwid;

  for (k=0;k<colwid-1;k++)
    chline[k] = ' ';
  str_value(i,j,type,nx,data,line);
  len = strlen(line);
  for (k=0;k<len;k++)
    chline[k] = line[k];
  chline[len] = ' ';
  chline[colwid-1] = '|' | A_BOLD;
  chline[colwid] = '\0';
  mvwaddchnstr(win,j-joff,(i-ioff)*colwid,chline,colwid);
}
Пример #14
0
QString BytesHumanizer::toString(int precision) const {
    qreal value = m_value;

    int index = 0;
    for(int i=0;i<8;i++) {
        if(value <= 2048.0 && value >= -2048.0) {
            break;
        }
        value /= 1024.0;
        index++;
    }

    QString zero(precision,'0');
    QString str_value(QString("%1").arg(value,0,'f',precision));
    if (str_value.endsWith("."+zero)) {
        str_value = str_value.left(str_value.length()-1-zero.length());
    }

    return QString("%1 %2").arg(str_value).arg(labels[index]);
}
Пример #15
0
static VALUE *eval7(void)
{
	VALUE *v;

	if (!*G.args)
		bb_error_msg_and_die("syntax error");

	if (nextarg("(")) {
		G.args++;
		v = eval();
		if (!nextarg(")"))
			bb_error_msg_and_die("syntax error");
		G.args++;
		return v;
	}

	if (nextarg(")"))
		bb_error_msg_and_die("syntax error");

	return str_value(*G.args++);
}
Пример #16
0
void update_row(WINDOW *win, int y, int ioff, int joff,
		int type, int nx, void *data)
{
  char line[BUFSIZ];
  int len, k, d, i;
  chtype chline[BUFSIZ];
  extern int colwid, dcols;

  for (i=0;i<dcols;i++) {
    for (k=0;k<colwid-1;k++)
      chline[k] = ' ';
    str_value(i+ioff,y+joff,type,nx,data,line);
    len = strlen(line);
    for (k=0;k<len;k++)
      chline[k] = line[k];
    chline[len] = ' ';
    chline[colwid-1] = '|' | A_BOLD;
    chline[colwid] = '\0';
    mvwaddchnstr(win,y,i*colwid,chline,colwid);
  }
}
Пример #17
0
void update_col(WINDOW *win, int x, int ioff, int joff,
		int type, int nx, void *data)
{
  char line[BUFSIZ];
  int len, k, d, j;
  chtype chline[BUFSIZ];
  extern int colwid, drows;

  for (j=0;j<drows;j++) {
    for (k=0;k<colwid-1;k++)
      chline[k] = ' ';
    str_value(x+ioff,j+joff,type,nx,data,line);
    len = strlen(line);
    for (k=0;k<len;k++)
      chline[k] = line[k];
    chline[len] = ' ';
    chline[colwid-1] = '|' | A_BOLD;
    chline[colwid] = '\0';
    mvwaddchnstr(win,j,x*colwid,chline,colwid);
  }
}
Пример #18
0
struct t_hashtable *
weechat_js_object_to_hashtable (v8::Handle<v8::Object> obj,
                                int size,
                                const char *type_keys,
                                const char *type_values)
{
    struct t_hashtable *hashtable;
    unsigned int i;
    v8::Handle<v8::Array> keys;
    v8::Handle<v8::Value> key, value;

    hashtable = weechat_hashtable_new (size, type_keys, type_values,
                                       NULL, NULL);

    if (!hashtable)
        return NULL;

    keys = obj->GetPropertyNames();
    for (i = 0; i < keys->Length(); i++)
    {
        key = keys->Get(i);
        value = obj->Get(key);
        v8::String::Utf8Value str_key(key);
        v8::String::Utf8Value str_value(value);
        if (strcmp (type_values, WEECHAT_HASHTABLE_STRING) == 0)
        {
            weechat_hashtable_set (hashtable, *str_key, *str_value);
        }
        else if (strcmp (type_values, WEECHAT_HASHTABLE_POINTER) == 0)
        {
            weechat_hashtable_set (hashtable, *str_key,
                                   plugin_script_str2ptr (weechat_js_plugin,
                                                          NULL, NULL,
                                                          *str_value));
        }
    }

    return hashtable;
}
Пример #19
0
/*
 * Find object address for an object that is attached to a relation.
 *
 * Note that we take only an ACCESS_SHR_LOCK on the relation.  We need not
 * pass down the lockmode_t from get_object_address(), because that is the lock
 * mode for the object itself, not the relation to which it is attached.
 */
static struct objaddr
get_objaddr_relobj(
	objtype_e objtype,
	struct list *objname,
	struct relation** relp)
{
	struct objaddr address;
	struct relation* relation = NULL;
	int nnames;
	const char *depname;

	/* Extract name of dependent object. */
	depname = str_value(lfirst(list_tail(objname)));

	/* Separate relation name from dependent object name. */
	nnames = list_length(objname);
	if (nnames < 2) {
		oid_t reloid;

		/*
		 * For compatibility with very old releases, we sometimes allow users
		 * to attempt to specify a rule without mentioning the relation name.
		 * If there's only rule by that name in the entire database, this will
		 * work.  But objects other than rules don't get this special
		 * treatment.
		 */
		if (objtype != OBJECT_RULE)
			elog(ERROR, "must specify relation and object name");

		address.classId = RewriteRelationId;
		address.objectId = get_rewrite_oid_without_relid(depname, &reloid);
		address.objectSubId = 0;

		/*
		 * Caller is expecting to get back the relation, even though we
		 * didn't end up using it to find the rule.
		 */
		relation = heap_open(reloid, ACCESS_SHR_LOCK);
	} else {
		struct list* relname;
		oid_t reloid;

		/* Extract relation name and open relation. */
		relname = list_truncate(list_copy(objname), nnames - 1);
		relation = heap_open_rngv(nl_to_range_var(relname), ACCESS_SHR_LOCK);
		reloid = REL_ID(relation);

		switch (objtype) {
		case OBJECT_RULE:
			address.classId = RewriteRelationId;
			address.objectId = get_rewrite_oid(reloid, depname, false);
			address.objectSubId = 0;
			break;

		case OBJECT_TRIGGER:
			address.classId = TriggerRelationId;
			address.objectId = get_trigger_oid(reloid, depname, false);
			address.objectSubId = 0;
			break;

		case OBJECT_CONSTRAINT:
			address.classId = ConstraintRelationId;
			address.objectId = get_constraint_oid(reloid, depname, false);
			address.objectSubId = 0;
			break;

		default:
			elog(ERROR, "unrecognized objtype: %d", (int) objtype);
			/* placate compiler, which doesn't know elog won't return */
			address.classId = INVALID_OID;
			address.objectId = INVALID_OID;
			address.objectSubId = 0;
		}
	}

	/* Done. */
	*relp = relation;
	return address;
}
Пример #20
0
/*
 * Find an struct objaddr for a type of object that is identified by an
 * unqualified name.
 */
static struct objaddr
get_objaddr_unqualified(objtype_e objtype, struct list *qualname)
{
	const char *name;
	struct objaddr address;

	/*
	 * The types of names handled by this function are not permitted to be
	 * schema-qualified or catalog-qualified.
	 */
	if (list_length(qualname) != 1) {
		const char *msg;

		switch (objtype) {
		case OBJECT_DATABASE:
			msg = gettext_noop("database name cannot be qualified");
			break;

		case OBJECT_EXTENSION:
			msg = gettext_noop("extension name cannot be qualified");
			break;

		case OBJECT_TABLESPACE:
			msg = gettext_noop("tablespace name cannot be qualified");
			break;

		case OBJECT_ROLE:
			msg = gettext_noop("role name cannot be qualified");
			break;

		case OBJECT_SCHEMA:
			msg = gettext_noop("schema name cannot be qualified");
			break;

		case OBJECT_LANGUAGE:
			msg = gettext_noop("language name cannot be qualified");
			break;

		case OBJECT_FDW:
			msg = gettext_noop("foreign-data wrapper name cannot be qualified");
			break;

		case OBJECT_FOREIGN_SERVER:
			msg = gettext_noop("server name cannot be qualified");
			break;

		default:
			elog(ERROR, "unrecognized objtype: %d", (int) objtype);
			msg = NULL;		/* placate compiler */
		}

		ereport(ERROR, (
		errcode(E_SYNTAX_ERROR),
		errmsg("%s", _(msg))));
	}

	/* Format is valid, extract the actual name. */
	name = str_value(linitial(qualname));

	/* Translate name to OID. */
	switch (objtype) {
	case OBJECT_DATABASE:
		address.classId = DatabaseRelationId;
		address.objectId = get_db_oid(name, false);
		address.objectSubId = 0;
		break;

	case OBJECT_EXTENSION:
		address.classId = ExtensionRelationId;
		address.objectId = get_extension_oid(name, false);
		address.objectSubId = 0;
		break;

	case OBJECT_TABLESPACE:
		address.classId = TableSpaceRelationId;
		address.objectId = tbs_get_oid(name, false);
		address.objectSubId = 0;
		break;

	case OBJECT_ROLE:
		address.classId = AuthIdRelationId;
		address.objectId = get_role_oid(name, false);
		address.objectSubId = 0;
		break;

	case OBJECT_SCHEMA:
		address.classId = NAMESPACE_RELATION_ID;
		address.objectId = get_ns_oid(name, false);
		address.objectSubId = 0;
		break;

	case OBJECT_LANGUAGE:
		address.classId = LanguageRelationId;
		address.objectId = get_lang_oid(name, false);
		address.objectSubId = 0;
		break;

	case OBJECT_FDW:
		address.classId = ForeignDataWrapperRelationId;
		address.objectId = get_fdw_oid(name, false);
		address.objectSubId = 0;
		break;

	case OBJECT_FOREIGN_SERVER:
		address.classId = ForeignServerRelationId;
		address.objectId = get_foreign_server_oid(name, false);
		address.objectSubId = 0;
		break;

	default:
		elog(ERROR, "unrecognized objtype: %d", (int) objtype);
		/* placate compiler, which doesn't know elog won't return */
		address.classId = INVALID_OID;
		address.objectId = INVALID_OID;
		address.objectSubId = 0;
	}

	return address;
}
Пример #21
0
static int is_end(){
    if (str_value() == 0)
        return 1;
    else
        return 0;
}
Пример #22
0
static void next_non_space_char(){
    while (str_value() == ' '|| str_value()=='\n')
        next_char();
}
Пример #23
0
CS_IMPLEMENT_APPLICATION

int main (int argc, char *argv[])
{
  iObjectRegistry* objreg = csInitializer::CreateEnvironment (argc, argv);
  if (! objreg)
  {
    csFPrintf (stderr, "Failed to create environment!\n");
    return 1;
  }

  bool ok = csInitializer::RequestPlugins (objreg,
    CS_REQUEST_REPORTER,
    CS_REQUEST_REPORTERLISTENER,
    CS_REQUEST_PLUGIN ("crystalspace.script.perl5", iScript),
    CS_REQUEST_END);
  if (! ok)
  {
    csFPrintf (stderr, "Failed to load plugins!\n");
    return 2;
  }

  if (csCommandLineHelper::CheckHelp (objreg))
  {
    csCommandLineHelper::Help (objreg);
    return 0;
  }

  {
    csRef<iScript> script = csQueryRegistry<iScript> (objreg);
    if (! script)
    {
      csFPrintf (stderr, "Failed to find perl5 plugin!\n");
      return 3;
    }

    ok = script->LoadModule ("cspace");
    //ok = script->LoadModule ("scripts/perl5", "cspace.pm");
    if (! ok)
    {
      csFPrintf (stderr, "Failed to load perl5 cspace module!\n");
      return 4;
    }

    csInitializer::OpenApplication (objreg);

    //====================================================================//
    csPrintf ("Testing RValue/Store/Retrieve:\n");

    int test_int = 3;
    float test_float = 3.0;
    double test_double = 3.0;
    bool test_bool = true;
    const char *test_str = "hello";

    csPrintf ("  Int: ");
    csRef<iScriptValue> int_value (script->RValue (test_int));
    ok = script->Store("i", int_value);
    int_value.AttachNew (script->Retrieve ("i"));
    csPrintf ("%d == %d\n", test_int, int_value->GetInt ());

    csPrintf ("  Float: ");
    csRef<iScriptValue> float_value (script->RValue (test_float));
    ok = script->Store("f", float_value);
    float_value.AttachNew (script->Retrieve ("f"));
    csPrintf ("%f == %f\n", test_float, float_value->GetFloat ());

    csPrintf ("  Double: ");
    csRef<iScriptValue> double_value (script->RValue (test_double));
    ok = script->Store("d", double_value);
    double_value.AttachNew (script->Retrieve ("d"));
    csPrintf ("%lf == %lf\n", test_double, double_value->GetDouble ());

    csPrintf ("  String: ");
    csRef<iScriptValue> str_value (script->RValue (test_str));
    ok = script->Store("s", str_value);
    str_value.AttachNew (script->Retrieve ("s"));
    csPrintf ("%s == %s\n", test_str, str_value->GetString ()->GetData ());

    csPrintf ("  Bool: ");
    csRef<iScriptValue> bool_value (script->RValue (test_bool));
    ok = script->Store("b", bool_value);
    bool_value.AttachNew (script->Retrieve ("b"));
    csPrintf ("%s == %s\n\n", test_bool ? "true" : "false",
			      bool_value->GetBool () ? "true" : "false");

    //====================================================================//
    csPrintf ("Testing Remove:\n");

    ok = script->Remove ("i") && script->Remove ("f") && script->Remove ("d")
      && script->Remove ("s") && script->Remove ("b");
    csPrintf ("  %s\n", ok ? "ok" : "failed");

    int_value.AttachNew (script->Retrieve ("i"));
    csPrintf ("  %s\n", int_value.IsValid () ? "failed" : "ok");

    //====================================================================//
    csPrintf ("Testing New(csVector3):\n");

    csRef<iScriptObject> obj (script->New ("csVector3"));
    csPrintf ("  %s\n", obj.IsValid () ? "ok" : "failed");

    //====================================================================//
    csPrintf ("Testing GetClass/IsA:\n");

    csRef<iString> classname (obj->GetClass ());
    csPrintf ("  %s\n", classname->GetData ());

    csPrintf ("  %s\n", obj->IsA ("csVector3") ? "ok" : "failed");

    //====================================================================//
    csPrintf ("Testing Set/Get:\n");

    csPrintf ("  %f == ", float_value->GetFloat ());

    ok = obj->Set ("x", float_value);
    float_value.AttachNew (obj->Get ("x"));

    csPrintf ("%f\n", float_value->GetFloat ());

    //====================================================================//
    csPrintf ("Testing Call(csVector3::Set):\n");

    csRefArray<iScriptValue> args;
    args.Push (float_value);

    csRef<iScriptValue> ret (obj->Call ("Set", args));
    csPrintf ("  %f\n", float_value->GetFloat ());

    //====================================================================//
    csPrintf ("Testing Call(csVector3::Norm):\n");

    ret.AttachNew (obj->Call ("Norm"));
    csPrintf ("  %f\n", ret->GetFloat ());

    //====================================================================//
    csPrintf ("Testing GetPointer:\n");

    csVector3 &vector = * (csVector3 *) obj->GetPointer ();

    vector.Normalize ();

    csPrintf ("  %f %f %f\n", vector[0], vector[1], vector[2]);
    csPrintf ("  ok\n");

    csPrintf ("All Done!\n");
  }

  csInitializer::DestroyApplication (objreg);
  return 0;
}
Пример #24
0
 static int json2field(const rapidjson::Value* json, Message* msg, const FieldDescriptor *field, std::string& err)
 {
     const Reflection *ref = msg->GetReflection();
     const bool repeated = field->is_repeated();
     switch (field->cpp_type())
     {
         case FieldDescriptor::CPPTYPE_INT32:
         {
             if (json->GetType() != rapidjson::kNumberType)
             {
                 RETURN_ERR(ERR_INVALID_JSON, "Not a number");
             }
             if (repeated)
             {
                 ref->AddInt32(msg, field, (int32_t) json->GetInt());
             }
             else
             {
                 ref->SetInt32(msg, field, (int32_t) json->GetInt());
             }
             break;
         }
         case FieldDescriptor::CPPTYPE_UINT32:
         {
             if (json->GetType() != rapidjson::kNumberType)
             {
                 RETURN_ERR(ERR_INVALID_JSON, "Not a number");
             }
             if (repeated)
             {
                 ref->AddUInt32(msg, field, json->GetUint());
             }
             else
             {
                 ref->SetUInt32(msg, field, json->GetUint());
             }
             break;
         }
         case FieldDescriptor::CPPTYPE_INT64:
         {
             if (json->GetType() != rapidjson::kNumberType)
             {
                 RETURN_ERR(ERR_INVALID_JSON, "Not a number");
             }
             if (repeated)
             {
                 ref->AddInt64(msg, field, json->GetInt64());
             }
             else
             {
                 ref->SetInt64(msg, field, json->GetInt64());
             }
             break;
         }
         case FieldDescriptor::CPPTYPE_UINT64:
         {
             if (json->GetType() != rapidjson::kNumberType)
             {
                 RETURN_ERR(ERR_INVALID_JSON, "Not a number");
             }
             if (repeated)
             {
                 ref->AddUInt64(msg, field, json->GetUint64());
             }
             else
             {
                 ref->SetUInt64(msg, field, json->GetUint64());
             }
             break;
         }
         case FieldDescriptor::CPPTYPE_DOUBLE:
         {
             if (json->GetType() != rapidjson::kNumberType)
             {
                 RETURN_ERR(ERR_INVALID_JSON, "Not a number");
             }
             if (repeated)
             {
                 ref->AddDouble(msg, field, json->GetDouble());
             }
             else
             {
                 ref->SetDouble(msg, field, json->GetDouble());
             }
             break;
         }
         case FieldDescriptor::CPPTYPE_FLOAT:
         {
             if (json->GetType() != rapidjson::kNumberType)
             {
                 RETURN_ERR(ERR_INVALID_JSON, "Not a number");
             }
             if (repeated)
             {
                 ref->AddFloat(msg, field, json->GetDouble());
             }
             else
             {
                 ref->SetFloat(msg, field, json->GetDouble());
             }
             break;
         }
         case FieldDescriptor::CPPTYPE_BOOL:
         {
             if (json->GetType() != rapidjson::kTrueType && json->GetType() != rapidjson::kFalseType)
             {
                 RETURN_ERR(ERR_INVALID_JSON, "Not a bool");
             }
             bool v = json->GetBool();
             if (repeated)
             {
                 ref->AddBool(msg, field, v);
             }
             else
             {
                 ref->SetBool(msg, field, v);
             }
             break;
         }
         case FieldDescriptor::CPPTYPE_STRING:
         {
             if (json->GetType() != rapidjson::kStringType)
             {
                 RETURN_ERR(ERR_INVALID_JSON, "Not a string");
             }
             const char* value = json->GetString();
             uint32_t str_size = json->GetStringLength();
             std::string str_value(value, str_size);
             if (field->type() == FieldDescriptor::TYPE_BYTES)
             {
                 if (repeated)
                 {
                     ref->AddString(msg, field, b64_decode(str_value));
                 }
                 else
                 {
                     ref->SetString(msg, field, b64_decode(str_value));
                 }
             }
             else
             {
                 if (repeated)
                 {
                     ref->AddString(msg, field, str_value);
                 }
                 else
                 {
                     ref->SetString(msg, field, str_value);
                 }
             }
             break;
         }
         case FieldDescriptor::CPPTYPE_MESSAGE:
         {
             Message *mf = (repeated) ? ref->AddMessage(msg, field) : ref->MutableMessage(msg, field);
             return parse_json(json, mf, err);
         }
         case FieldDescriptor::CPPTYPE_ENUM:
         {
             const EnumDescriptor *ed = field->enum_type();
             const EnumValueDescriptor *ev = 0;
             if (json->GetType() == rapidjson::kNumberType)
             {
                 ev = ed->FindValueByNumber(json->GetInt());
             }
             else if (json->GetType() == rapidjson::kStringType)
             {
                 ev = ed->FindValueByName(json->GetString());
             }
             else
                 RETURN_ERR(ERR_INVALID_JSON, "Not an integer or string");
             if (!ev)
                 RETURN_ERR(ERR_INVALID_JSON, "Enum value not found");
             if (repeated)
             {
                 ref->AddEnum(msg, field, ev);
             }
             else
             {
                 ref->SetEnum(msg, field, ev);
             }
             break;
         }
         default:
             break;
     }
     return 0;
 }
Пример #25
0
/*
 * EnumValuesCreate
 *		Create an entry in pg_enum for each of the supplied enum values.
 *
 * vals is a list of value_n strings.
 */
void EnumValuesCreate(oid_t enumTypeOid, struct list *vals)
{
	struct relation *pg_enum;
	struct name enumlabel;
	oid_t *oids;
	int elemno;
	int num_elems;
	datum_t	values[Natts_pg_enum];
	bool nulls[Natts_pg_enum];
	struct list_cell *lc;
	struct heap_tuple *tup;

	num_elems = list_length(vals);

	/*
	 * We do not bother to check the list of values for duplicates. If you
	 * have any, you'll get a less-than-friendly unique-index violation. It
	 * is probably not worth trying harder.
	 */
	pg_enum = heap_open(EnumRelationId, ROW_EXCL_LOCK);

	/*
	 * Allocate OIDs for the enum's members.
	 *
	 * While this method does not absolutely guarantee that we generate no
	 * duplicate OIDs (since we haven't entered each oid into the table before
	 * allocating the next), trouble could only occur if the OID counter wraps
	 * all the way around before we finish. Which seems unlikely.
	 */
	oids = (oid_t *) palloc(num_elems * sizeof(oid_t));
	for (elemno = 0; elemno < num_elems; elemno++) {
		/*
		 * We assign even-numbered OIDs to all the new enum labels.  This
		 * tells the comparison functions the OIDs are in the correct sort
		 * order and can be compared directly.
		 */
		oid_t new_oid;

		do {
			new_oid = get_new_oid(pg_enum);
		} while (new_oid & 1);
		oids[elemno] = new_oid;
	}

	/* sort them, just in case OID counter wrapped from high to low */
	qsort(oids, num_elems, sizeof(oid_t), oid_cmp);

	/* and make the entries */
	memset(nulls, false, sizeof(nulls));

	elemno = 0;
	foreach(lc, vals) {
		char *lab;

		lab = str_value(lfirst(lc));

		/*
		 * labels are stored in a name field, for easier syscache lookup, so
		 * check the length to make sure it's within range.
		 */
		if (strlen(lab) > (NAMEDATALEN - 1))
			ereport(ERROR, (
			errcode(E_INVALID_NAME),
			errmsg("invalid enum label \"%s\"", lab),
			errdetail("Labels must be %d characters or less.",
				NAMEDATALEN - 1)));

		values[Anum_pg_enum_enumtypid - 1] = OID_TO_D(enumTypeOid);
		values[Anum_pg_enum_enumsortorder - 1] = FLOAT4_TO_D(elemno + 1);
		namestrcpy(&enumlabel, lab);
		values[Anum_pg_enum_enumlabel - 1] = NAME_TO_D(&enumlabel);

		tup = heap_form_tuple(REL_DESC(pg_enum), values, nulls);
		HT_SET_OID(tup, oids[elemno]);

		simple_heap_insert(pg_enum, tup);
		cat_update_indexes(pg_enum, tup);
		heap_free_tuple(tup);

		elemno++;
	}
Пример #26
0
/* STRING 型の value を作成する */
value* str_new(char* const val)
{
  value* res = value_new();
  *res = str_value(val);
  return res;
}
Пример #27
0
static svn_error_t *
entries_dump(const char *dir_path, svn_wc_adm_access_t *related, apr_pool_t *pool)
{
  svn_wc_adm_access_t *adm_access = NULL;
  apr_hash_t *entries;
  apr_hash_index_t *hi;
  svn_boolean_t locked;
  svn_error_t *err;
  svn_wc_context_t *wc_ctx = NULL;
  const char *dir_abspath;

  err = svn_wc_adm_open3(&adm_access, related, dir_path, FALSE, 0,
                         NULL, NULL, pool);
  if (!err)
    {
      SVN_ERR(svn_wc__context_create_with_db(&wc_ctx, NULL,
                                             svn_wc__adm_get_db(adm_access),
                                             pool));
      SVN_ERR(svn_dirent_get_absolute(&dir_abspath, dir_path, pool));

      SVN_ERR(svn_wc_locked2(NULL, &locked, wc_ctx, dir_abspath, pool));
      SVN_ERR(svn_wc_entries_read(&entries, adm_access, TRUE, pool));
    }
  else if (err && err->apr_err == SVN_ERR_WC_LOCKED
           && related
           && ! strcmp(dir_path, svn_wc_adm_access_path(related)))
    {
      /* Common caller error: Can't open a baton when there is one. */
      svn_error_clear(err);

      SVN_ERR(svn_wc__context_create_with_db(&wc_ctx, NULL,
                                             svn_wc__adm_get_db(related),
                                             pool));
      SVN_ERR(svn_dirent_get_absolute(&dir_abspath, dir_path, pool));

      SVN_ERR(svn_wc_locked2(NULL, &locked, wc_ctx, dir_abspath, pool));
      SVN_ERR(svn_wc_entries_read(&entries, related, TRUE, pool));
    }
  else
    {
      const char *lockfile_path;
      svn_node_kind_t kind;

      /* ### Should svn_wc_adm_open3 be returning UPGRADE_REQUIRED? */
      if (err->apr_err != SVN_ERR_WC_NOT_DIRECTORY)
        return err;
      svn_error_clear(err);
      adm_access = NULL;
      SVN_ERR(svn_dirent_get_absolute(&dir_abspath, dir_path, pool));
      SVN_ERR(svn_wc__read_entries_old(&entries, dir_abspath, pool, pool));
      lockfile_path = svn_dirent_join_many(pool, dir_path,
                                           svn_wc_get_adm_dir(pool),
                                           "lock", SVN_VA_NULL);
      SVN_ERR(svn_io_check_path(lockfile_path, &kind, pool));
      locked = (kind == svn_node_file);
    }

  for (hi = apr_hash_first(pool, entries); hi; hi = apr_hash_next(hi))
    {
      const char *key = apr_hash_this_key(hi);
      const svn_wc_entry_t *entry = apr_hash_this_val(hi);

      SVN_ERR_ASSERT(strcmp(key, entry->name) == 0);

      printf("e = Entry()\n");
      str_value("name", entry->name);
      int_value("revision", entry->revision);
      str_value("url", entry->url);
      str_value("repos", entry->repos);
      str_value("uuid", entry->uuid);
      int_value("kind", entry->kind);
      int_value("schedule", entry->schedule);
      bool_value("copied", entry->copied);
      bool_value("deleted", entry->deleted);
      bool_value("absent", entry->absent);
      bool_value("incomplete", entry->incomplete);
      str_value("copyfrom_url", entry->copyfrom_url);
      int_value("copyfrom_rev", entry->copyfrom_rev);
      str_value("conflict_old", entry->conflict_old);
      str_value("conflict_new", entry->conflict_new);
      str_value("conflict_wrk", entry->conflict_wrk);
      str_value("prejfile", entry->prejfile);
      /* skip: text_time */
      /* skip: prop_time */
      /* skip: checksum */
      int_value("cmt_rev", entry->cmt_rev);
      /* skip: cmt_date */
      str_value("cmt_author", entry->cmt_author);
      str_value("lock_token", entry->lock_token);
      str_value("lock_owner", entry->lock_owner);
      str_value("lock_comment", entry->lock_comment);
      /* skip: lock_creation_date */
      /* skip: has_props */
      /* skip: has_prop_mods */
      /* skip: cachable_props */
      /* skip: present_props */
      str_value("changelist", entry->changelist);
      /* skip: working_size */
      /* skip: keep_local */
      int_value("depth", entry->depth);
      /* skip: tree_conflict_data */
      bool_value("file_external", entry->file_external_path != NULL);
      /* skip: file_external_peg_rev */
      /* skip: file_external_rev */
      bool_value("locked", locked && *entry->name == '\0');
      printf("entries['%s'] = e\n", (const char *)key);
    }

  if (wc_ctx)
    SVN_ERR(svn_wc_context_destroy(wc_ctx));

  if (adm_access)
    SVN_ERR(svn_wc_adm_close2(adm_access, pool));

  return SVN_NO_ERROR;
}
Пример #28
0
static VALUE *eval6(void)
{
	static const char keywords[] ALIGN1 =
		"quote\0""length\0""match\0""index\0""substr\0";

	VALUE *r, *i1, *i2;
	static VALUE *l = NULL;
	static VALUE *v = NULL;
	int key = *G.args ? index_in_strings(keywords, *G.args) + 1 : 0;

	if (key == 0) /* not a keyword */
		return eval7();
	G.args++; /* We have a valid token, so get the next argument.  */
	if (key == 1) { /* quote */
		if (!*G.args)
			bb_error_msg_and_die("syntax error");
		return str_value(*G.args++);
	}
	if (key == 2) { /* length */
		r = eval6();
		tostring(r);
		v = int_value(strlen(r->u.s));
		freev(r);
	} else
		l = eval6();

	if (key == 3) { /* match */
		r = eval6();
		v = docolon(l, r);
		freev(l);
		freev(r);
	}
	if (key == 4) { /* index */
		r = eval6();
		tostring(l);
		tostring(r);
		v = int_value(strcspn(l->u.s, r->u.s) + 1);
		if (v->u.i == (arith_t) strlen(l->u.s) + 1)
			v->u.i = 0;
		freev(l);
		freev(r);
	}
	if (key == 5) { /* substr */
		i1 = eval6();
		i2 = eval6();
		tostring(l);
		if (!toarith(i1) || !toarith(i2)
		 || i1->u.i > (arith_t) strlen(l->u.s)
		 || i1->u.i <= 0 || i2->u.i <= 0)
			v = str_value("");
		else {
			v = xmalloc(sizeof(VALUE));
			v->type = STRING;
			v->u.s = xstrndup(l->u.s + i1->u.i - 1, i2->u.i);
		}
		freev(l);
		freev(i1);
		freev(i2);
	}
	return v;
}