Exemple #1
0
TypedValue HHVM_FUNCTION(serialize_memoize_param, TypedValue param) {
  // Memoize throws in the emitter if any function parameters are references, so
  // we can just assert that the param is cell here
  assertx(param.m_type != KindOfRef);
  auto const type = param.m_type;

  if (isStringType(type)) {
    auto const str = param.m_data.pstr;
    if (str->empty()) {
      return make_tv<KindOfPersistentString>(s_emptyStrMemoKey.get());
    } else if ((unsigned char)str->data()[0] < '~') {
      // fb_compact_serialize always returns a string with the high-bit set in
      // the first character. Furthermore, we use ~ to begin all our special
      // constants, so anything less than ~ can't collide. There's no worry
      // about int-like strings because we use dicts (which don't perform key
      // coercion) to store the memoized values.
      str->incRefCount();
      return param;
    }
  } else if (isContainer(param) && getContainerSize(param) == 0) {
    return make_tv<KindOfPersistentString>(s_emptyArrMemoKey.get());
  } else if (type == KindOfUninit || type == KindOfNull) {
    return make_tv<KindOfPersistentString>(s_nullMemoKey.get());
  } else if (type == KindOfBoolean) {
    return make_tv<KindOfPersistentString>(
      param.m_data.num ? s_trueMemoKey.get() : s_falseMemoKey.get()
    );
  } else if (type == KindOfInt64) {
    return param;
  }

  return tvReturn(
    fb_compact_serialize(tvAsCVarRef(&param),
                         FBCompactSerializeBehavior::MemoizeParam));
}
Exemple #2
0
char * ScilabObjects::getSingleString(int pos, void * pvApiCtx)
{
    SciErr err;
    int * addr = 0;
    char * str = 0;

    err = getVarAddressFromPosition(pvApiCtx, pos, &addr);
    if (err.iErr)
    {
        throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid String"));
    }

    if (!isStringType(pvApiCtx, addr))
    {
        throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("A single string expected"));
    }

    if (!isScalar(pvApiCtx, addr))
    {
        throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("A single String expected"));
    }

    if (getAllocatedSingleString(pvApiCtx, addr, &str))
    {
        throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid String"));
    }

    return str;
}
Exemple #3
0
int String__strncpy(void *str1, void *str2, int n)
{
	int l1 = strlen(*(void **)str1), l2 = strlen(*(void **)str2);
	char *string1Chars = getStringChars(str1);
	char *string2Chars = getStringChars(str2);
	int returnVal = 0;
	if (isStringType((void **)str1)) {
		String string1 = *(String *)str1;
		if (!(string1.LengthLimit >= MIN(n, l2))) {
			changeStringLength(string1, MIN(n, l2));
			/*  Return the number of extra characters */
			returnVal = MAX(n, l2);
		}
		int newLength = MIN(n, l2);
		string1.Length = newLength;
		string1Chars[newLength] = '\0';
	} else {
		if (l1 <= l1 + MIN(l2, n)) {
		} else {
			fprintf(stderr, "ERROR: stringnfuncs.c:String__strncpy: destination string too short\n");
			returnVal = l1 - MIN(l2, n); //Failure, result < 0
			return returnVal;
		}
	}
	memcpy(string1Chars, string2Chars, (MIN(n, l2)) * sizeof(char));
	return returnVal;
}
/*--------------------------------------------------------------------------*/
int getAllocatedSingleWideString(void* _pvCtx, int* _piAddress, wchar_t** _pwstData)
{
    SciErr sciErr = sciErrInit();
    int iRows = 0;
    int iCols = 0;
    int iLen = 0;

    if (isScalar(_pvCtx, _piAddress) == 0 || isStringType(_pvCtx, _piAddress) == 0)
    {
        addErrorMessage(&sciErr, API_ERROR_GET_ALLOC_SINGLE_WIDE_STRING, _("%s: Wrong type for input argument #%d: A single string expected.\n"), "getAllocatedSingleWideString", getRhsFromAddress(_pvCtx, _piAddress));
        printError(&sciErr, 0);
        return sciErr.iErr;
    }

    sciErr = getMatrixOfWideString(_pvCtx, _piAddress, &iRows, &iCols, &iLen, NULL);
    if (sciErr.iErr)
    {
        addErrorMessage(&sciErr, API_ERROR_GET_ALLOC_SINGLE_WIDE_STRING, _("%s: Unable to get argument data"), "getAllocatedSingleWideString");
        printError(&sciErr, 0);
        return sciErr.iErr;
    }

    *_pwstData = (wchar_t*)MALLOC(sizeof(wchar_t) * (iLen + 1)); //+1 for null termination

    sciErr = getMatrixOfWideString(_pvCtx, _piAddress, &iRows, &iCols, &iLen, _pwstData);
    if (sciErr.iErr)
    {
        addErrorMessage(&sciErr, API_ERROR_GET_ALLOC_SINGLE_WIDE_STRING, _("%s: Unable to get argument data"), "getAllocatedSingleWideString");
        printError(&sciErr, 0);
        FREE(*_pwstData);
        return sciErr.iErr;
    }

    return 0;
}
Exemple #5
0
ArrayData* ArrayCommon::ToKeyset(ArrayData* a, bool) {
  auto const size = a->size();
  if (!size) return staticEmptyKeysetArray();
  KeysetInit init{size};
  IterateV(
    a,
    [&](const TypedValue* v) {
      if (UNLIKELY(v->m_type == KindOfRef)) {
        if (v->m_data.pref->isReferenced()) {
          throwRefInvalidArrayValueException(init.toArray());
        }
        v = v->m_data.pref->tv();
        assertx(v->m_type != KindOfRef);
      }

      if (LIKELY(isStringType(v->m_type))) {
        init.add(v->m_data.pstr);
      } else if (LIKELY(isIntType(v->m_type))) {
        init.add(v->m_data.num);
      } else {
        throwInvalidArrayKeyException(v, init.toArray().get());
      }
    }
  );
  return init.create();
}
StringData* prepareAnyKey(TypedValue* tv) {
  if (isStringType(tv->m_type)) {
    StringData* str = tv->m_data.pstr;
    str->incRefCount();
    return str;
  } else {
    return tvAsCVarRef(tv).toString().detach();
  }
}
  bool DDLIndexPopulator::checkUnique( int idx, const erydbSystemCatalog::ColType& colType ) 
  {
    if (0 == idx)
	return true;
    //Get row of data as each column result data at idx
    size_t indexSize = fColNames.size();
    vector <uint64_t> rowIntData(indexSize);
    vector <string> rowStrData(indexSize);

    for (size_t i = 0; i < indexSize; ++i) 
    { 
      //if  ( isStringType(fUniqueColResultList[i]->columnType()) )
      if  ( isStringType(colType.colDataType) )
	  rowStrData[i] = fUniqueColResultList[i]->GetStringData(idx);
      else
	  rowIntData[i] = fUniqueColResultList[i]->GetData(idx);
    }
	//check if each value in the idx row is equal to each value in a previous row
	// i is the row; j is the column.
    bool unique = true;
    for (int i = 0; i < idx && unique; ++i)
    {
	bool equal = true;
	for (size_t j = 0; j < indexSize && equal; ++j)
	{
	  if ( isStringType(colType.colDataType) )
	  {
	    equal = fUniqueColResultList[j]->GetStringData(i) == rowStrData[j];
          }
	  else
          {
	    equal = (static_cast<uint64_t>(fUniqueColResultList[j]->GetData(i)) == rowIntData[j]);
          }
	}
	unique = ! equal;
    }
    if (! unique)
    {
	stringstream ss;
    	ss << idx;   
	logError("Unique Constraint violated on row: " + ss.str() );
    }
    return unique;
  }
Exemple #8
0
std::string& SourceRootInfo::initPhpRoot() {
  auto const v = php_global(s_SERVER).toArray().rvalAt(s_PHP_ROOT).unboxed();
  if (isStringType(v.type())) {
    *s_phproot.getCheck() = std::string(v.val().pstr->data()) + "/";
  } else {
    // Our best guess at the source root.
    *s_phproot.getCheck() = GetCurrentSourceRoot();
  }
  return *s_phproot.getCheck();
}
Exemple #9
0
QString Set<T>::toString(int index)
{
    QString temp;
    if (!isStringType(&pType[index]))
        temp.setNum(pType[index]);

    else
        temp = QString(pType[index]);
    return temp;
}//get a string for a single index.
Exemple #10
0
/* ========================================================================== */
int sci_bug_11106(char *fname)
{
    int* piAddr = NULL;
    char pstRet[64];

    getVarAddressFromPosition(pvApiCtx, 1, &piAddr);

    if (isStringType(pvApiCtx, piAddr))
    {
        //named check
        char* pstVar = NULL;
        getAllocatedSingleString(pvApiCtx, piAddr, &pstVar);

        if (isNamedListType(pvApiCtx, pstVar))
        {
            sprintf(pstRet, "%s", "isNamedList");
        }
        else if (isNamedTListType(pvApiCtx, pstVar))
        {
            sprintf(pstRet, "%s", "isNamedTList");
        }
        else if (isNamedMListType(pvApiCtx, pstVar))
        {
            sprintf(pstRet, "%s", "isNamedMList");
        }
        else
        {
            sprintf(pstRet, "%s", "unmanaged named type");
        }
        FREE(pstVar);
    }
    else
    {
        if (isListType(pvApiCtx, piAddr))
        {
            sprintf(pstRet, "%s", "isList");
        }
        else if (isTListType(pvApiCtx, piAddr))
        {
            sprintf(pstRet, "%s", "isTList");
        }
        else if (isMListType(pvApiCtx, piAddr))
        {
            sprintf(pstRet, "%s", "isMList");
        }
        else
        {
            sprintf(pstRet, "%s", "unmanaged type");
        }
    }
    createSingleString(pvApiCtx, Rhs + 1, pstRet);
    LhsVar(1) = Rhs + 1;
    return 0;
}
Exemple #11
0
Type keysetElemType(SSATmp* arr, SSATmp* idx) {
  assertx(arr->isA(TKeyset));
  assertx(!idx || idx->isA(TInt | TStr));

  if (arr->hasConstVal()) {
    // If both the array and idx are known statically, we can resolve it to the
    // precise type.
    if (idx && idx->hasConstVal(TInt)) {
      auto const idxVal = idx->intVal();
      auto const val = SetArray::NvGetInt(arr->keysetVal(), idxVal);
      return val ? Type(val->m_type) : TBottom;
    }

    if (idx && idx->hasConstVal(TStr)) {
      auto const idxVal = idx->strVal();
      auto const val = SetArray::NvGetStr(arr->keysetVal(), idxVal);
      return val ? Type(val->m_type) : TBottom;
    }

    // Otherwise we can constrain the type according to the union of all the
    // types present in the keyset.
    Type type{TBottom};
    SetArray::Iterate(
      SetArray::asSet(arr->keysetVal()),
      [&](const TypedValue* k) {
        // Ignore values which can't correspond to the key's type
        if (isIntType(k->m_type)) {
          if (!idx || idx->type().maybe(TInt)) type |= Type(k->m_type);
        } else {
          assertx(isStringType(k->m_type));
          if (!idx || idx->type().maybe(TStr)) type |= Type(k->m_type);
        }
      }
    );

    // The key is always the value, so, for instance, if there's nothing but
    // strings in the keyset, we know an int idx can't access a valid value.
    if (idx) {
      if (idx->isA(TInt)) type &= TInt;
      if (idx->isA(TStr)) type &= TStr;
    }
    return type;
  }

  // Keysets always contain strings or integers. We can further constrain this
  // if we know the idx type, as the key is always the value.
  auto type = TStr | TInt;
  if (idx) {
    if (idx->isA(TInt)) type &= TInt;
    if (idx->isA(TStr)) type &= TStr;
  }
  if (arr->isA(TPersistentKeyset)) type &= TUncountedInit;
  return type;
}
bool BaseSet::OffsetContains(ObjectData* obj, const TypedValue* key) {
  assert(key->m_type != KindOfRef);
  auto set = static_cast<BaseSet*>(obj);
  if (key->m_type == KindOfInt64) {
    return set->contains(key->m_data.num);
  }
  if (isStringType(key->m_type)) {
    return set->contains(key->m_data.pstr);
  }
  throwBadValueType();
  return false;
}
bool BaseMap::OffsetContains(ObjectData* obj, const TypedValue* key) {
  assert(key->m_type != KindOfRef);
  auto map = static_cast<BaseMap*>(obj);
  if (key->m_type == KindOfInt64) {
    return map->contains(key->m_data.num);
  } else if (isStringType(key->m_type)) {
    return map->contains(key->m_data.pstr);
  } else {
    throwBadKeyType();
    return false;
  }
}
void BaseSet::OffsetUnset(ObjectData* obj, const TypedValue* key) {
  assert(key->m_type != KindOfRef);
  auto set = static_cast<BaseSet*>(obj);
  if (key->m_type == KindOfInt64) {
    set->remove(key->m_data.num);
    return;
  }
  if (isStringType(key->m_type)) {
    set->remove(key->m_data.pstr);
    return;
  }
  throwBadValueType();
}
Exemple #15
0
TCResult ast::SliceOp::typecheck(sst::TypecheckState* fs, fir::Type* inferred)
{
	fs->pushLoc(this);
	defer(fs->popLoc());

	fs->pushAnonymousTree();
	defer(fs->popTree());

	auto array = this->expr->typecheck(fs).expr();
	auto ty = array->type;

	fs->enterSubscript(array);
	defer(fs->leaveSubscript());

	fir::Type* elm = 0;
	if(ty->isDynamicArrayType() || ty->isArraySliceType() || ty->isArrayType())
		elm = ty->getArrayElementType();

	else if(ty->isStringType())
		elm = fir::Type::getInt8();

	else if(ty->isPointerType())
		elm = ty->getPointerElementType();

	else
		error(array, "invalid type '%s' for slice operation", ty);

	auto begin = this->start ? this->start->typecheck(fs, fir::Type::getInt64()).expr() : 0;
	auto end = this->end ? this->end->typecheck(fs, fir::Type::getInt64()).expr() : 0;

	if(begin && !begin->type->isIntegerType())
		error(begin, "expected integer type for start index of slice; found '%s'", begin->type);

	if(end && !end->type->isIntegerType())
		error(end, "expected integer type for end index of slice; found '%s'", end->type);

	//* how it goes:
	// 1. strings and dynamic arrays are always sliced mutably.
	// 2. slices of slices naturally inherit their mutability.
	// 3. arrays are sliced immutably.
	// 4. pointers inherit their mutability as well.

	bool ismut = sst::getMutabilityOfSliceOfType(ty);

	auto ret = util::pool<sst::SliceOp>(this->loc, fir::ArraySliceType::get(elm, ismut));
	ret->expr = array;
	ret->begin = begin;
	ret->end = end;

	return TCResult(ret);
}
bool BaseMap::OffsetEmpty(ObjectData* obj, const TypedValue* key) {
  assert(key->m_type != KindOfRef);
  auto map = static_cast<BaseMap*>(obj);
  TypedValue* result;
  if (key->m_type == KindOfInt64) {
    result = map->get(key->m_data.num);
  } else if (isStringType(key->m_type)) {
    result = map->get(key->m_data.pstr);
  } else {
    throwBadKeyType();
    result = nullptr;
  }
  return result ? !cellToBool(*result) : true;
}
Exemple #17
0
/*--------------------------------------------------------------------------*/
int sci_xinit(char * fname, void *pvApiCtx)
{
    SciErr err;
    int * addr = 0;
    char * path = 0;
    char * realPath = 0;

    CheckInputArgument(pvApiCtx, 1, 1);

    err = getVarAddressFromPosition(pvApiCtx, 1, &addr);
    if (err.iErr)
    {
        printError(&err, 0);
        Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1);
        return 0;
    }

    if (!isStringType(pvApiCtx, addr) || !checkVarDimension(pvApiCtx, addr, 1, 1))
    {
        Scierror(999, gettext("%s: Wrong type for input argument #%d: string expected.\n"), fname, 1);
        return 0;
    }

    if (getAllocatedSingleString(pvApiCtx, addr, &path) != 0)
    {
        Scierror(999, _("%s: No more memory.\n"), fname);
        return 0;
    }

    realPath = expandPathVariable(path);

    if (realPath)
    {
        org_scilab_modules_graphic_export::Driver::setPath(getScilabJavaVM(), realPath);
        FREE(realPath);
    }
    else
    {
        Scierror(999, _("%s: Invalid path: %s.\n"), fname, path);
        return 0;
    }

    freeAllocatedSingleString(path);

    LhsVar(1) = 0;
    PutLhsVar();

    return 0;
}
Exemple #18
0
bool TypeConstraint::checkTypeAliasNonObj(const TypedValue* tv) const {
  assert(tv->m_type != KindOfObject);
  assert(isObject());

  auto p = getTypeAliasOrClassWithAutoload(m_namedEntity, m_typeName);
  auto td = p.first;
  auto c = p.second;

  // Common case is that we actually find the alias:
  if (td) {
    if (td->nullable && tv->m_type == KindOfNull) return true;
    auto result = annotCompat(tv->m_type, td->type,
      td->klass ? td->klass->name() : nullptr);
    switch (result) {
      case AnnotAction::Pass: return true;
      case AnnotAction::Fail: return false;
      case AnnotAction::CallableCheck:
        return is_callable(tvAsCVarRef(tv));
      case AnnotAction::DictCheck:
        return tv->m_data.parr->isDict();
      case AnnotAction::VecCheck:
        return tv->m_data.parr->isVecArray();
      case AnnotAction::ObjectCheck: break;
    }
    assert(result == AnnotAction::ObjectCheck);
    assert(td->type == AnnotType::Object);
    // Fall through to the check below, since this could be a type
    // alias to an enum type
    c = td->klass;
  }

  // Otherwise, this isn't a proper type alias, but it *might* be a
  // first-class enum. Check if the type is an enum and check the
  // constraint if it is. We only need to do this when the underlying
  // type is not an object, since only int and string can be enums.
  if (c && isEnum(c)) {
    auto dt = c->enumBaseTy();
    // For an enum, if the underlying type is mixed, we still require
    // it is either an int or a string!
    if (dt) {
      return equivDataTypes(*dt, tv->m_type);
    } else {
      return isIntType(tv->m_type) || isStringType(tv->m_type);
    }
  }
  return false;
}
Exemple #19
0
Variant ArrayUtil::CountValues(const Array& input) {
  Array ret = Array::Create();
  for (ArrayIter iter(input); iter; ++iter) {
    auto const inner = iter.secondRval().unboxed();
    if (isIntType(inner.type()) || isStringType(inner.type())) {
      if (!ret.exists(inner.tv())) {
        ret.set(inner.tv(), make_tv<KindOfInt64>(1));
      } else {
        ret.set(inner.tv(),
                make_tv<KindOfInt64>(ret[inner.tv()].toInt64() + 1));
      }
    } else {
      raise_warning("Can only count STRING and INTEGER values!");
    }
  }
  return ret;
}
Exemple #20
0
/*--------------------------------------------------------------------------*/
int sci_scitlist(char *fname, unsigned long fname_len)
{
    if (Rhs >= 1)
    {
        #define RLIST_FIELDNAME "r"
        SciErr sciErr;
        int *piAddressVarOne = NULL;


        sciErr = getVarAddressFromPosition(pvApiCtx, 1, &piAddressVarOne);
        if(sciErr.iErr)
        {
            printError(&sciErr, 0);
            Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1);
            return 0;
        }

        if (isStringType(pvApiCtx, piAddressVarOne))
        {
            int m = 0;
            int n = 0;
            char **pStrs = NULL;
            BOOL bIsRfield = FALSE;

            if (getAllocatedMatrixOfString(pvApiCtx, piAddressVarOne, &m, &n, &pStrs) != 0)
            {
                Scierror(999, _("%s: No more memory.\n"), fname);
                return 0;
            }

            bIsRfield = (BOOL)(strcmp(pStrs[0], RLIST_FIELDNAME) == 0);
            freeAllocatedMatrixOfString(m, n, pStrs);
            pStrs = NULL;

            // it is not allowed to create a tlist of type 'r'
            // 'r' type reserved to rlist
            if (bIsRfield)
            {
                Scierror(999, _("%s: Can not create a tlist with input argument #%d.\n"), fname, 1);
                return 0;
            }
        }
    }
	C2F(scilist)(fname, fname_len);
	return 0;
}
Exemple #21
0
bool cellSame(Cell c1, Cell c2) {
  assert(cellIsPlausible(c1));
  assert(cellIsPlausible(c2));

  bool const null1 = isNullType(c1.m_type);
  bool const null2 = isNullType(c2.m_type);
  if (null1 && null2) return true;
  if (null1 || null2) return false;

  switch (c1.m_type) {
    case KindOfBoolean:
    case KindOfInt64:
      if (c2.m_type != c1.m_type) return false;
      return c1.m_data.num == c2.m_data.num;

    case KindOfDouble:
      if (c2.m_type != c1.m_type) return false;
      return c1.m_data.dbl == c2.m_data.dbl;

    case KindOfPersistentString:
    case KindOfString:
      if (!isStringType(c2.m_type)) return false;
      return c1.m_data.pstr->same(c2.m_data.pstr);

    case KindOfPersistentArray:
    case KindOfArray:
      if (!isArrayType(c2.m_type)) return false;
      return c1.m_data.parr->equal(c2.m_data.parr, true);

    case KindOfObject:
      return c2.m_type == KindOfObject &&
        c1.m_data.pobj == c2.m_data.pobj;

    case KindOfResource:
      return c2.m_type == KindOfResource &&
        c1.m_data.pres == c2.m_data.pres;

    case KindOfUninit:
    case KindOfNull:
    case KindOfRef:
    case KindOfClass:
      break;
  }
  not_reached();
}
Exemple #22
0
Variant ArrayUtil::Reverse(const Array& input, bool preserve_keys /* = false */) {
  if (input.empty()) {
    return empty_array();
  }

  auto ret = Array::Create();
  auto pos_limit = input->iter_end();
  for (ssize_t pos = input->iter_last(); pos != pos_limit;
       pos = input->iter_rewind(pos)) {
    auto const key = input->nvGetKey(pos);
    if (preserve_keys || isStringType(key.m_type)) {
      ret.setWithRef(key, input->atPos(pos), true);
    } else {
      ret.appendWithRef(input->atPos(pos));
    }
  }
  return ret;
}
QVariant QGpgMECryptoConfigEntry::stringToValue( const QString& str, bool unescape ) const
{
  const bool isString = isStringType();

  if ( isList() ) {
    if ( argType() == ArgType_None ) {
        bool ok = true;
        const QVariant v = str.isEmpty() ? 0U : str.toUInt( &ok ) ;
        if ( !ok )
            kWarning(5150) << "list-of-none should have an unsigned int as value:" << str;
        return v;
    }
    QList<QVariant> lst;
    QStringList items = str.split( ',', QString::SkipEmptyParts );
    for( QStringList::const_iterator valit = items.constBegin(); valit != items.constEnd(); ++valit ) {
      QString val = *valit;
      if ( isString ) {
        if ( val.isEmpty() ) {
          lst << QVariant( QString() );
          continue;
        }
        else if ( unescape ) {
          if( val[0] != '"' ) // see README.gpgconf
            kWarning(5150) <<"String value should start with '\"' :" << val;
          val = val.mid( 1 );
        }
      }
      lst << QVariant( unescape ? gpgconf_unescape( val ) : val );
    }
    return lst;
  } else { // not a list
    QString val( str );
    if ( isString ) {
      if ( val.isEmpty() )
        return QVariant( QString() ); // not set  [ok with lists too?]
      else if ( unescape ) {
        if( val[0] != '"' ) // see README.gpgconf
          kWarning(5150) <<"String value should start with '\"' :" << val;
        val = val.mid( 1 );
      }
    }
    return QVariant( unescape ? gpgconf_unescape( val ) : val );
  }
}
QString QGpgMECryptoConfigEntry::toString( bool escape ) const
{
  // Basically the opposite of stringToValue
  if ( isStringType() ) {
    if ( mValue.isNull() )
      return QString();
    else if ( isList() ) { // string list
      QStringList lst = mValue.toStringList();
      if ( escape ) {
        for( QStringList::iterator it = lst.begin(); it != lst.end(); ++it ) {
          if ( !(*it).isNull() )
            *it = gpgconf_escape( *it ).prepend( "\"" );
        }
      }
      QString res = lst.join( "," );
      //kDebug(5150) <<"toString:" << res;
      return res;
    } else { // normal string
      QString res = mValue.toString();
      if ( escape )
        res = gpgconf_escape( res ).prepend( "\"" );
      return res;
    }
  }
  if ( !isList() ) // non-list non-string
  {
    if ( mArgType == ArgType_None ) {
      return mValue.toBool() ? QString::fromLatin1( "1" ) : QString();
    } else { // some int
      Q_ASSERT( mArgType == ArgType_Int || mArgType == ArgType_UInt );
      return mValue.toString(); // int to string conversion
    }
  }

  // Lists (of other types than strings)
  if ( mArgType == ArgType_None )
    return QString::number( numberOfTimesSet() );
  QStringList ret;
  QList<QVariant> lst = mValue.toList();
  for( QList<QVariant>::const_iterator it = lst.constBegin(); it != lst.constEnd(); ++it ) {
      ret << (*it).toString(); // QVariant does the conversion
  }
  return ret.join( "," );
}
Exemple #25
0
Type dictElemType(SSATmp* arr, SSATmp* idx) {
  assertx(arr->isA(TDict));
  assertx(!idx || idx->isA(TInt | TStr));

  if (arr->hasConstVal()) {
    // If both the array and idx are known statically, we can resolve it to the
    // precise type.
    if (idx && idx->hasConstVal(TInt)) {
      auto const idxVal = idx->intVal();
      auto const val = MixedArray::NvGetIntDict(arr->dictVal(), idxVal);
      return val ? Type(val->m_type) : TBottom;
    }

    if (idx && idx->hasConstVal(TStr)) {
      auto const idxVal = idx->strVal();
      auto const val = MixedArray::NvGetStrDict(arr->dictVal(), idxVal);
      return val ? Type(val->m_type) : TBottom;
    }

    // Otherwise we can constrain the type according to the union of all the
    // types present in the dict.
    Type type{TBottom};
    MixedArray::IterateKV(
      MixedArray::asMixed(arr->dictVal()),
      [&](const TypedValue* k, const TypedValue* v) {
        // Ignore values which can't correspond to the key's type
        if (isIntType(k->m_type)) {
          if (!idx || idx->type().maybe(TInt)) type |= Type(v->m_type);
        } else if (isStringType(k->m_type)) {
          if (!idx || idx->type().maybe(TStr)) type |= Type(v->m_type);
        }
      }
    );
    return type;
  }

  // Dicts always contain initialized cells
  return arr->isA(TPersistentDict) ? TUncountedInit : TInitCell;
}
Exemple #26
0
/*--------------------------------------------------------------------------*/
int sci_fullpath(char *fname,unsigned long fname_len)
{
    SciErr sciErr;
    int *piAddressVarOne = NULL;
    char **pStVarOne = NULL;
    int mOne = 0, nOne = 0;
    int mnOne = 0;

    char **pStFullPath = NULL;
    int i = 0;

    Rhs = Max(Rhs, 0);
    CheckRhs(1,1);
    CheckLhs(0,1);

    sciErr = getVarAddressFromPosition(pvApiCtx, 1, &piAddressVarOne);
    if(sciErr.iErr)
    {
        printError(&sciErr, 0);
        Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1);
        return 0;
    }

    if (!isStringType(pvApiCtx, piAddressVarOne))
    {
        if (isEmptyMatrix(pvApiCtx, piAddressVarOne))
        {
            createEmptyMatrix(pvApiCtx, Rhs + 1);
            LhsVar(1) = Rhs + 1;
            PutLhsVar()
        }
        else
        {
            Scierror(999,_("%s: Wrong type for input argument #%d: String expected.\n"), fname, 1);
        }
        return 0;
    }
Exemple #27
0
/*--------------------------------------------------------------------------*/
int getStackArgumentAsBoolean(void* _pvCtx, int* _piAddr)
{
    if (isScalar(_pvCtx, _piAddr))
    {
        if (isDoubleType(_pvCtx, _piAddr))
        {
            double dbl = 0;
            getScalarDouble(_pvCtx, _piAddr, &dbl);
            return ((int)dbl == 0 ? FALSE : TRUE);
        }
        else if (isBooleanType(_pvCtx, _piAddr))
        {
            int i = 0;
            getScalarBoolean(_pvCtx, _piAddr, &i);
            return (i == 0 ? FALSE : TRUE);
        }
        else if (isStringType(_pvCtx, _piAddr))
        {
            int ret = 0;
            char* pst = NULL;
            if (getAllocatedSingleString(_pvCtx, _piAddr, &pst))
            {
                return -1;
            }

            if (stricmp(pst, "on") == 0)
            {
                ret = TRUE;
            }

            freeAllocatedSingleString(pst);

            return ret;
        }
    }
    return -1;
}
Exemple #28
0
/* Set fftw wisdom
*
* Scilab Syntax :
*   -->set_fftw_wisdom(txt);
*
* Input : a scilab string matrix
*
* Output : Nothing or an error messsage if
*          wisdom can't be read by fftw
*
*/
int sci_set_fftw_wisdom(char *fname, void* pvApiCtx)
{
    SciErr sciErr;
    char **Str1 = NULL;
    char *Str = NULL;
    int m1 = 0, n1 = 0;
    int len = 0, k = 0;
    int j = 0;
    int i = 0;
    int* piAddr1 = NULL;
    int* piLen = NULL;

    if (withMKL())
    {
        Scierror(999, _("%s: MKL fftw library does not implement wisdom functions yet.\n"), fname);
        return 0;
    }

    CheckInputArgument(pvApiCtx, 1, 1);

    //get variable address
    sciErr = getVarAddressFromPosition(pvApiCtx, 1, &piAddr1);
    if (sciErr.iErr)
    {
        printError(&sciErr, 0);
        return 1;
    }

    if (isStringType(pvApiCtx, piAddr1) == 0)
    {
        Scierror(999, _("%s: Wrong type for input argument #%d: string expected.\n"), fname, 1);
        return 1;
    }

    //fisrt call to retrieve dimensions
    sciErr = getMatrixOfString(pvApiCtx, piAddr1, &m1, &n1, NULL, NULL);
    if (sciErr.iErr)
    {
        printError(&sciErr, 0);
        return 1;
    }

    piLen = (int*)MALLOC(sizeof(int) * m1 * n1);

    //second call to retrieve length of each string
    sciErr = getMatrixOfString(pvApiCtx, piAddr1, &m1, &n1, piLen, NULL);
    if (sciErr.iErr)
    {
        printError(&sciErr, 0);
        return 1;
    }

    Str1 = (char**)MALLOC(sizeof(char*) * m1 * n1);
    for (i = 0 ; i < m1 * n1 ; i++)
    {
        Str1[i] = (char*)MALLOC(sizeof(char) * (piLen[i] + 1));//+ 1 for null termination
    }

    //third call to retrieve data
    sciErr = getMatrixOfString(pvApiCtx, piAddr1, &m1, &n1, piLen, Str1);
    if (sciErr.iErr)
    {
        printError(&sciErr, 0);
        return 1;
    }

    for (j = 0; j < m1 * n1; j++)
    {
        len += (int)strlen(Str1[j]) + 1;

        if (Str)
        {
            Str = (char *)REALLOC(Str, sizeof(char) * (len));
        }
        else
        {
            Str = (char *)MALLOC(sizeof(char) * (len));
        }

        if (Str == NULL)
        {
            freeArrayOfString(Str1, m1 * n1);
            Scierror(999, _("%s: Cannot allocate more memory.\n"), fname);
            return 1;
        }

        for (i = 0; i < (int)strlen(Str1[j]); i++)
        {
            Str[k + i] = Str1[j][i];
        }
        Str[k + strlen(Str1[j])] = '\n';
        k += (int)strlen(Str1[j]) + 1;
    }
    Str[k - 1] = '\0';

    freeArrayOfString(Str1, m1 * n1);

    if (!(call_fftw_import_wisdom_from_string(Str)))
    {
        FREE(Str);
        Str = NULL;
        Scierror(999, _("%s: Wrong value for input argument #%d: a valid wisdom expected.\n"), fname, 1);
        return 1;
    }
    FREE(Str);
    Str = NULL;

    AssignOutputVariable(pvApiCtx, 1) = 0;
    ReturnArguments(pvApiCtx);
    return 0;
}
Exemple #29
0
void staticArrayStreamer(const ArrayData* ad, std::ostream& out) {
  out << "array(";
  if (!ad->empty()) {
    bool comma = false;
    for (ArrayIter it(ad); !it.end(); it.next()) {
      if (comma) {
        out << ",";
      } else {
        comma = true;
      }
      Variant key = it.first();

      // Key.
      if (isIntType(key.getType())) {
        out << *key.getInt64Data();
      } else if (isStringType(key.getType())) {
        out << "\""
            << escapeStringForCPP(key.getStringData()->data(),
                                  key.getStringData()->size())
            << "\"";
      } else {
        assert(false);
      }

      out << "=>";

      Variant val = it.second();

      // Value.
      [&] {
        switch (val.getType()) {
          case KindOfUninit:
          case KindOfNull:
            out << "null";
            return;
          case KindOfBoolean:
            out << (val.toBoolean() ? "true" : "false");
            return;
          case KindOfInt64:
            out << *val.getInt64Data();
            return;
          case KindOfDouble:
            out << *val.getDoubleData();
            return;
          case KindOfPersistentString:
          case KindOfString:
            out << "\""
                << escapeStringForCPP(val.getStringData()->data(),
                                      val.getStringData()->size())
                << "\"";
            return;
          case KindOfPersistentArray:
          case KindOfArray:
            staticArrayStreamer(val.getArrayData(), out);
            return;
          case KindOfObject:
          case KindOfResource:
          case KindOfRef:
          case KindOfClass:
            not_reached();
        }
      }();
    }
  }
  out << ")";
}
/*--------------------------------------------------------------------------*/
int sci_tempname(char *fname, void* pvApiCtx)
{
    SciErr sciErr;
    wchar_t *wcprefix = NULL;
    wchar_t *wcTempFilename = NULL;

    //Rhs = Max(Rhs, 0);
    CheckRhs(0, 1);
    CheckLhs(1, 1);

    if (Rhs == 0)
    {
        wcprefix = (wchar_t *)MALLOC(sizeof(wchar_t) * (wcslen(DEFAULT_PREFIX) + 1));
        wcscpy(wcprefix, DEFAULT_PREFIX);
    }
    else
    {
        int *piAddressVarOne = NULL;

        sciErr = getVarAddressFromPosition(pvApiCtx, 1, &piAddressVarOne);
        if (sciErr.iErr)
        {
            printError(&sciErr, 0);
            Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1);
            return 0;
        }

        if (!isScalar(pvApiCtx, piAddressVarOne))
        {
            Scierror(999, _("%s: Wrong size for input argument #%d: A scalar expected.\n"), fname, 1);
            return 0;
        }

        if (isStringType(pvApiCtx, piAddressVarOne))
        {
            if (getAllocatedSingleWideString(pvApiCtx, piAddressVarOne, &wcprefix))
            {
                if (wcprefix)
                {
                    freeAllocatedSingleWideString(wcprefix);
                }

                Scierror(999, _("%s: Memory allocation error.\n"), fname);
                return 0;
            }

#if _MSC_VER
            if (wcslen(wcprefix) > 3)
            {
                freeAllocatedSingleWideString(wcprefix);
                Scierror(999, _("%s: Wrong size for input argument #%d: A string (3 characters max.) expected.\n"), fname, 1);
                return 0;
            }
#endif
        }
        else
        {
            freeAllocatedSingleWideString(wcprefix);
            Scierror(999, _("%s: Wrong type for input argument #%d: string expected.\n"), fname, 1);
            return 0;
        }
    }

    wcTempFilename = createtempfilenameW(wcprefix, TRUE);
    freeAllocatedSingleWideString(wcprefix);
    if (wcTempFilename == NULL)
    {
        Scierror(999, _("%s: Memory allocation error.\n"), fname);
        return 0;
    }

    if (createSingleWideString(pvApiCtx, Rhs + 1, wcTempFilename))
    {
        FREE(wcTempFilename);
        Scierror(999, _("%s: Memory allocation error.\n"), fname);
        return 0;
    }

    FREE(wcTempFilename);
    LhsVar(1) = Rhs + 1;
    PutLhsVar();
    return 0;
}