Beispiel #1
0
[[noreturn]]
static void extra_kwargs(FunctionSignature& signature, PyObject* kwargs, ssize_t num_pos_args) {
  PyObject *key, *value;
  ssize_t pos = 0;

  while (PyDict_Next(kwargs, &pos, &key, &value)) {
    if (!THPUtils_checkString(key)) {
      throw TypeError("keywords must be strings");
    }

    auto param_idx = find_param(signature, key);
    if (param_idx < 0) {
      throw TypeError("%s() got an unexpected keyword argument '%s'",
          signature.name.c_str(), THPUtils_unpackString(key).c_str());
    }

    if (param_idx < num_pos_args) {
      throw TypeError("%s() got multiple values for argument '%s'",
          signature.name.c_str(), THPUtils_unpackString(key).c_str());
    }
  }

  // this should never be hit
  throw TypeError("invalid keyword arguments");
}
PyObject* create_Group(PyObject* args){
  if (PySequence_Length(args) == 0){
    throw TypeError("A group must contain at least one object");
  }

  // Use either the function arguments as the sequence of objects, or
  // a single sequence-argument as the sequence. i.e. allow both
  // Group(a, b, c, d) and Group([a,b,c,d])
  PyObject* sequence = (PySequence_Length(args) == 1 &&
    PySequence_Check(PySequence_GetItem(args, 0))) ?
    PySequence_GetItem(args, 0) :
    args;

  const auto n = PySequence_Length(sequence);
  // Prevent empty seguence arguments groups, i.e. Group([])
  if (n == 0){
    throw TypeError("A group must contain at least one object.");
  }

  objects_t faintObjects;
  for (int i = 0; i != n; i++){
    PyObject* object = PySequence_GetItem(sequence, i);
    if (!PyObject_IsInstance(object, (PyObject*)&ShapeType)){
      throw TypeError("Unsupported item in list");
    }

    faintObjects.push_back(proxy_shape(object));
  }

  Object* group = create_composite_object_raw(faintObjects, Ownership::OWNER);
  return create_Shape(group);
}
Beispiel #3
0
  Time Time::fromIso(const std::string& s)
  {
    Time ret;
    const char* d = s.data();
    try
    {
      if (s.size() == 12
        && d[2] == ':'
        && d[5] == ':'
        && d[8] == '.')
      {
        ret.set(getNumber2(d), getNumber2(d + 3), getNumber2(d + 6),
                getNumber3(d + 9));
      }
      else if (s.size() == 8
        && d[2] == ':'
        && d[5] == ':')
      {
        ret.set(getNumber2(d), getNumber2(d + 3), getNumber2(d + 6));
      }
      else
        throw TypeError();
    }
    catch (const TypeError&)
    {
      throw TypeError("failed to convert string \"" + s + "\" into time");
    }

    return ret;
  }
Beispiel #4
0
[[noreturn]]
static void extra_args(const FunctionSignature& signature, ssize_t nargs) {
  auto max_pos_args = signature.max_pos_args;
  auto min_args = signature.min_args;
  if (min_args != max_pos_args) {
    throw TypeError("%s() takes from %d to %d positional arguments but %d were given",
        signature.name.c_str(), min_args, max_pos_args, nargs);
  }
  throw TypeError("%s() takes %d positional argument%s but %d %s given",
      signature.name.c_str(),
      max_pos_args, max_pos_args == 1 ? "" : "s",
      nargs, nargs == 1 ? "was" : "were");
}
Beispiel #5
0
struct InstrSeq * doArrayAssign( char * name, struct ExprRes * index, struct ExprRes * val){
    struct SymEntry *e;
    if( global ){
        e = FindName(locTable, name);
        if( !e){
            e = FindName(table, name);
        }
    }
    else{
        e = FindName(table, name);
    }
    struct Vtype * vtype = ((struct Vtype *)e->Attributes);
    struct InstrSeq * code;
    int reg = AvailTmpReg();
    char * buffer;
    if (!e){
        WriteIndicator(GetCurrentColumn());
        WriteMessage("Undeclared variable");
    }
    if(index->Type != TYPE_INT){
        TypeError();
    }
    else if( val->Type != -1 && ((vtype->Type ==  TYPE_BOOLARR &&  val->Type != TYPE_BOOL) || (vtype->Type == TYPE_INTARR && val->Type != TYPE_INT ))){
        TypeError();
    }
    buffer = RegOff(0, TmpRegName(reg));
    code = val->Instrs;
    AppendSeq(code, index->Instrs);
    // change for locality later
    if (! vtype->Local){
        AppendSeq( code, GenInstr( NULL, "la", TmpRegName(reg), name, NULL));
         
    }
    else {
        AppendSeq(code, GenInstr(NULL, "addi", TmpRegName(reg), "$sp", Imm(vtype->StackIndex)));
    }
    
    
    
    AppendSeq( code, GenInstr( NULL, "mul", TmpRegName(index->Reg), TmpRegName(index->Reg), "4"));
    AppendSeq( code, GenInstr(NULL, "add", TmpRegName(reg), TmpRegName(reg), TmpRegName(index->Reg)));
    AppendSeq( code, GenInstr(NULL, "sw", TmpRegName(val->Reg), buffer, NULL));
    ReleaseTmpReg(val->Reg);
    ReleaseTmpReg(index->Reg);
    ReleaseTmpReg(reg);
    free(val);
    free(index);

    return code;
    
}
/* method: "get_text_height(s)\n
Fixme!" */
static coord Shape_get_text_height(const Object& self){
  auto txt = dynamic_cast<const ObjText*>(&self);
  if (txt == nullptr){
    throw TypeError("This object does not have text attributes.");
  }
  return txt->RowHeight();
}
Beispiel #7
0
struct InstrSeq * doPrintsp(struct ExprRes * Expr){
    if(Expr->Type != TYPE_INT){
        TypeError();
    }
    struct InstrSeq * code;
    code = Expr->Instrs;
    char * end = GenLabel();
    char * next = GenLabel();
    int i = AvailTmpReg();
    int one = AvailTmpReg();


    AppendSeq(code, GenInstr(NULL, "addi", TmpRegName(one), "$0", "1"));
    AppendSeq(code, GenInstr(NULL, "blt", TmpRegName(Expr->Reg), "$0", end));
    AppendSeq(code, GenInstr(NULL, "li", TmpRegName(i), "0", NULL));
    AppendSeq(code, GenInstr(next, NULL,NULL,NULL,NULL));
   
    AppendSeq(code, GenInstr(NULL, "li", "$v0", "4", NULL));
    AppendSeq(code, GenInstr(NULL, "la", "$a0", "_sp", NULL));
    AppendSeq(code, GenInstr(NULL, "syscall", NULL, NULL,NULL));

    AppendSeq(code, GenInstr(NULL, "addi", TmpRegName(i), TmpRegName(i), "1"));
    AppendSeq(code, GenInstr(NULL, "blt", TmpRegName(i), TmpRegName(Expr->Reg), next));
    
    AppendSeq(code, GenInstr(end, NULL,NULL,NULL,NULL));
    ReleaseTmpReg(i);
    ReleaseTmpReg(one);
    ReleaseTmpReg(Expr->Reg);
    free(Expr);
    free(end);
    free(next);
    
    return code;

}
Beispiel #8
0
int asgn_op ( )
{
    descriptor *src;
    descriptor *dest;
    int		status;


    src  = pop ( );
    dest = top ( );
    src  = deref (src);


    if (!assignable (dest)) {
	TypeError ("cannot assign to", NULL, dest, NULL, F_False);
	RecycleData (src);
	return 1;
    }

    dest = deref (dest);
    src = CollapseMatrix (src);
    status = AssignData (dest, &src);
    RecycleData (src);
    D_Temp (dest) = F_False;

    return status;
}
Beispiel #9
0
int fail_op ( )
{
    Address	offset;
    descriptor *d;


    d = pop ( );
    d = CoerceData (deref (d), T_Double);
    offset = fetch (pc ++).addr;


    if (D_Type (d) != T_Double) {
        TypeError ("in conditional context", d, NULL, NULL, F_False);
        RecycleData (d);
        return 1;
    }

    if (*D_Double (d) == 0) {
        RecycleData (d);
        pc += offset;
        d = push ( );
        D_Type    (d) = T_Null;
        D_Temp    (d) = F_False;
        D_Trapped (d) = F_False;
        D_Pointer (d) = NULL;
    } else
        RecycleData (d);

    return 0;
}
Beispiel #10
0
 inline void
 Node::append(Node* newNode) {
   Array* a = dynamic_cast<Array*>(this);
   if (!a)
     throw TypeError("array expected");
   a->a.push_back(newNode);
 }
Beispiel #11
0
 void Exception::type_error(STATE, object_type type, Object* object,
                                  const char* reason) {
   // We code for TypeError being raised defensively, so it's ok, to raise it
   // since someone close by will catch it and propogate it back to ruby
   // properly.
   throw TypeError(type, object, reason);
 }
Beispiel #12
0
   //
   // operator Value * Value
   //
   Value operator * (Value const &l, Value const &r)
   {
      if(l.v == ValueBase::Fixed && r.v == ValueBase::Fixed) return l.vFixed * r.vFixed;
      if(l.v == ValueBase::Float && r.v == ValueBase::Float) return l.vFloat * r.vFloat;

      throw TypeError();
   }
Beispiel #13
0
   //
   // operator Value *= Value
   //
   Value &operator *= (Value &l, Value const &r)
   {
      if(l.v == ValueBase::Fixed && r.v == ValueBase::Fixed) return l.vFixed *= r.vFixed, l;
      if(l.v == ValueBase::Float && r.v == ValueBase::Float) return l.vFloat *= r.vFloat, l;

      throw TypeError();
   }
Beispiel #14
0
Value*
SnapPoint_cf(Value** arg_list, int count)
{
	check_arg_count_with_keys(SnapPoint, 1, count);
	def_snap_types();
	IPoint2 out;
	IPoint2 loc = to_ipoint2(arg_list[0]);

	Value	*val = key_arg(snapType);
	int		flags = (val == &unsupplied) ? 0 : GetID(snapTypes, elements(snapTypes), val);

	Value *snapPlane = key_arg(snapPlane);
	Matrix3* plane = NULL;
	if (snapPlane != &unsupplied) {
		if (!snapPlane->is_kind_of(class_tag(Matrix3Value)))
			throw TypeError (_T("snapPlane requires a Matrix3 value"), snapPlane);

		Matrix3Value* mv = static_cast<Matrix3Value*>(snapPlane);
		plane = new Matrix3(mv->m);
	}
	Point3	ret = MAXScript_interface->GetActiveViewExp().SnapPoint(loc, out, plane, flags);
	if (plane != NULL)
		delete plane;
	return new Point3Value(ret);
}
Beispiel #15
0
void PythonArgParser::print_error(PyObject* args, PyObject* kwargs, PyObject* parsed_args[]) {
  auto num_args = PyTuple_GET_SIZE(args) + (kwargs ? PyDict_Size(kwargs) : 0);
  std::vector<int> plausible_idxs;
  ssize_t i = 0;
  for (auto& signature : signatures_) {
    if (num_args >= signature.min_args && num_args <= signature.max_args && !signature.hidden) {
      plausible_idxs.push_back(i);
    }
    i++;
  }

  if (plausible_idxs.size() == 1) {
    auto& signature = signatures_[plausible_idxs[0]];
    signature.parse(args, kwargs, parsed_args, true);
  }

  std::vector<std::string> options;
  for (auto& signature : signatures_) {
    if (!signature.hidden) {
      options.push_back(signature.toString());
    }
  }

  auto msg = torch::format_invalid_args(args, kwargs, function_name + "()", options);
  throw TypeError("%s", msg.c_str());
}
Beispiel #16
0
T object<Ops>::require() const
{
	if (!check<T>())
		throw TypeError(type());

	return T(id());
}
Beispiel #17
0
 inline unsigned short getNumber2(const char* s)
 {
   if (!std::isdigit(s[0])
     || !std::isdigit(s[1]))
     throw TypeError();
   return (s[0] - '0') * 10
        + (s[1] - '0');
 }
/* method: "get_text_lines()->(s,...)\n
Returns the evaluated text from a Text-object split into lines. Takes
the bounding rectangle in consideration, so that the lines are split in
the same way as they appear in Faint." */
static text_lines_t Shape_get_text_lines(const Object& self){
  auto text = dynamic_cast<const ObjText*>(&self);
  if (!text){
    throw TypeError(space_sep(self.GetType(), "does not support text."));
  }

  NullExpressionContext ctx;
  return split_evaluated(ctx, *text);
}
Beispiel #19
0
std::unique_ptr<at::Storage> createStorage(PyObject* obj)
{
  auto it = py_storage_type_to_attype.find(Py_TYPE(obj));
  if (it == py_storage_type_to_attype.end()) {
    throw TypeError("not a storage '%s'", Py_TYPE(obj)->tp_name);
  }
  auto& type = *it->second;
  return type.unsafeStorageFromTH(((THPVoidStorage*)obj)->cdata, true);
}
Beispiel #20
0
   //
   // Type_Array::getSizeWordsVM
   //
   Exp::CRef Type_Array::getSizeWordsVM() const
   {
      auto wordBytes = Target::GetWordBytes();

      if(wordBytes == 1)
         return Exp_MulSize::Create(base->getSizeWordsVM(), Exp_IRExp::Create_Size(size));

      throw TypeError();
   }
Beispiel #21
0
/****************************************************************
  obj の ivname というインスタンス変数に *cval を代入する
  ivname が NULL の場合は、obj を配列とみなし、push する
  cval から ruby VALUE への変換ヒントは fmt で与える。
****************************************************************/
int cp_set1(VALUE obj, char *fmt, char *ivname, void *cval)
{
  char at_name[100];
  int len, c;
  VALUE val;

  switch (*fmt){
  case 'b':
    dprintf(("converting %d into BOOL\n", *(int*)cval));
    val = (*(int*)cval ? TRUE : FALSE);
    len = sizeof(int);
    break;
  case 'c':
    dprintf(("converting %d into uchar\n", *(unsigned char*)cval));
    val = INT2FIX(*(unsigned char *)cval);
    len = sizeof(unsigned char);
    break;
  case 'i':
    dprintf(("converting %d into FIXNUM\n", *(int*)cval));
    val = INT2FIX(*(int*)cval);
    len = sizeof(int);
    break;
  case 't':
    dprintf(("converting %d into Time\n", ((struct tm*)cval)->tm_year));
    val = TM2TIME((struct tm*)cval);
    len = sizeof(struct tm);
    break;
  case 's':
    dprintf(("converting into String\n"));
    if ((c = atoi(fmt + 1)) > 0){
      val = str_new2((char*)cval != NULL ? (char*)cval : "");
      len = sizeof(char) * c;
    } else {
      val = str_new2(*(char**)cval != NULL ? *(char**)cval : "");
      len = sizeof(char*);
    }
    break;
  case 'v':
    dprintf(("converting %d into VALUE\n", (VALUE*)cval));
    val = *(VALUE*)cval;
    len = sizeof(VALUE);
    break;
  default:
    TypeError(ivname != NULL ? ivname : "???");
  }

  if (ivname == NULL) {
    Check_Type(obj, T_ARRAY);
    ary_push(obj, val);
  } else {
    iv_conv_name(ivname, at_name);
    rb_iv_set(obj, at_name, val);
  }

  return len;
}
Beispiel #22
0
const dynamic* dynamic::get_ptr(dynamic const& idx) const& {
  if (auto* parray = get_nothrow<Array>()) {
    if (!idx.isInt()) {
      throw TypeError("int64", idx.type());
    }
    if (idx < 0 || idx >= parray->size()) {
      return nullptr;
    }
    return &(*parray)[idx.asInt()];
  } else if (auto* pobject = get_nothrow<ObjectImpl>()) {
    auto it = pobject->find(idx);
    if (it == pobject->end()) {
      return nullptr;
    }
    return &it->second;
  } else {
    throw TypeError("object/array", type());
  }
}
Beispiel #23
0
  Date Date::fromIso(const std::string& s)
  {
    Date ret;
    const char* d = s.data();
    try
    {
      if (s.size() < 10
        || d[4] != '-'
        || d[7] != '-')
        throw TypeError();
      ret.set(getNumber4(d), getNumber2(d + 5), getNumber2(d + 8));
    }
    catch (const TypeError&)
    {
      throw TypeError("failed to convert string \"" + s + "\" into date");
    }

    return ret;
  }
Beispiel #24
0
static PyTensorType& get_tensor_type(THPDtype *dtype, THPLayout *layout, bool is_cuda) {
  auto it = std::find_if(tensor_types.begin(), tensor_types.end(),
    [dtype, layout, is_cuda](const PyTensorType& x) {
      return x.dtype == dtype && x.layout == layout && x.is_cuda == is_cuda;
    });
  if (it == tensor_types.end()) {
    throw TypeError("invalid dtype object");
  }
  return *it;
}
Beispiel #25
0
dynamic const& dynamic::at(dynamic const& idx) const& {
  if (auto* parray = get_nothrow<Array>()) {
    if (!idx.isInt()) {
      throw TypeError("int64", idx.type());
    }
    if (idx < 0 || idx >= parray->size()) {
      throw std::out_of_range("out of range in dynamic array");
    }
    return (*parray)[idx.asInt()];
  } else if (auto* pobject = get_nothrow<ObjectImpl>()) {
    auto it = pobject->find(idx);
    if (it == pobject->end()) {
      throw std::out_of_range(to<std::string>(
          "couldn't find key ", idx.asString(), " in dynamic object"));
    }
    return it->second;
  } else {
    throw TypeError("object/array", type());
  }
}
Beispiel #26
0
dynamic& dynamic::operator[](dynamic const& k) & {
  if (!isObject() && !isArray()) {
    throw TypeError("object/array", type());
  }
  if (isArray()) {
    return at(k);
  }
  auto& obj = get<ObjectImpl>();
  auto ret = obj.insert({k, nullptr});
  return ret.first->second;
}
Beispiel #27
0
struct ExprRes * doAnd(struct ExprRes * Res1, struct ExprRes * Res2){
    if(Res1->Type != TYPE_BOOL || Res2->Type != TYPE_BOOL){
        TypeError();
    }
    
    AppendSeq(Res1->Instrs, Res2->Instrs);
    AppendSeq(Res1->Instrs, GenInstr(NULL, "and", TmpRegName(Res1->Reg), TmpRegName(Res1->Reg), TmpRegName(Res2->Reg)));
    ReleaseTmpReg(Res2->Reg);
    free(Res2);
    return Res1;
}
Beispiel #28
0
static Tensor new_from_sequence(ScalarType scalarType, PyObject* data) {
  if (!PySequence_Check(data)) {
    throw TypeError("new(): data must be a sequence (got %s)", Py_TYPE(data)->tp_name);
  }
  if (THPUtils_checkString(data)) {
    throw TypeError("new(): invalid data type '%s'", Py_TYPE(data)->tp_name);
  }
#ifdef WITH_NUMPY
  if (PyArray_Check(data)) {
    return autograd::make_variable(tensor_from_numpy(data), false);
  }
#endif

  auto sizes = compute_sizes(data);
  auto tensor = autograd::make_variable(CPU(scalarType).tensor(sizes), false);
  recursive_store(
      (char*)tensor.data_ptr(), tensor.sizes(), tensor.strides(), 0,
      scalarType, tensor.type().elementSizeInBytes(), data);
  return tensor;
}
Beispiel #29
0
std::size_t dynamic::size() const {
  if (auto* ar = get_nothrow<Array>()) {
    return ar->size();
  }
  if (auto* obj = get_nothrow<ObjectImpl>()) {
    return obj->size();
  }
  if (auto* str = get_nothrow<std::string>()) {
    return str->size();
  }
  throw TypeError("array/object", type());
}
Beispiel #30
0
static THPObjectPtr get_storage_obj(const Type& type) {
  auto module_name = get_module(type.backend());
  auto module_obj = THPObjectPtr(PyImport_ImportModule(module_name));
  if (!module_obj) throw python_error();

  auto storage_name = std::string(at::toString(type.scalarType())) + "Storage";
  THPObjectPtr storage(PyObject_GetAttrString(module_obj.get(), storage_name.c_str()));
  if (!storage.get()) {
    throw TypeError("couldn't find storage object %s", storage_name.c_str());
  }
  return storage;
}