Example #1
0
StringVec SpeckleyNodes::getVarNames() const
{
    StringVec res;
    res.push_back("Nodes_Id");
    res.push_back("Nodes_Tag");
    return res;
}
Example #2
0
void processLDFlags(const String& ldFlags, StringVec& libs) {
    // Tokenize flags
    StringVec ldFlagTokens;
    tokenize(ldFlags, ldFlagTokens, " \t", "", "\"'", "", "", true, false);

    // Expand -Wl, and -Xlinker tokens to make parsing easier
    StringVec ldFlagsFixed;
    replaceWlArgs(ldFlagTokens, ldFlagsFixed);

    String savedToken;
    for (auto opt : ldFlagsFixed) {
        if (savedToken.empty()) {
            opt = reduceLinkerToken(opt);
            if (opt == "-library" || opt == "-framework") {
                savedToken = opt;
            } else if (strBeginsWith(opt, "-l")) {
                String libName = strEndsWith(opt, ".o") ? opt.substr(2) : "lib" + opt.substr(2) + ".?";
                libs.push_back(libName);
            } else if (strEndsWith(opt, ".a") || strEndsWith(opt, ".dylib") || strEndsWith(opt, ".o")) {
                libs.push_back(opt);
            }
        } else {
            if (savedToken == "-library") {
                libs.push_back(opt);
            } else if (savedToken == "-framework") {
                std::string frameworkName = opt.substr(0, opt.find(',')) + ".framework";
                libs.push_back(frameworkName);
            }
            savedToken.clear();
        }
    }
}
Example #3
0
StringVec SpeckleyElements::getVarNames() const
{
    StringVec res;
    res.push_back(name + string("_Id"));
    res.push_back(name + string("_Owner"));
    //res.push_back(name + string("_Tag"));
    return res;
}
Example #4
0
File: tools.cpp Project: Berze/sour
StringVec explodeString(const std::string& string, const std::string& separator)
{
	StringVec returnVector;
	size_t start = 0, end = 0;
	while((end = string.find(separator, start)) != std::string::npos)
	{
		returnVector.push_back(string.substr(start, end - start));
		start = end + separator.size();
	}

	returnVector.push_back(string.substr(start));
	return returnVector;
}
Example #5
0
StringVec explodeString(const std::string& inString, const std::string& separator, int32_t limit/* = -1*/)
{
	StringVec returnVector;
	std::string::size_type start = 0, end = 0;

	while (--limit != -1 && (end = inString.find(separator, start)) != std::string::npos) {
		returnVector.push_back(inString.substr(start, end - start));
		start = end + separator.size();
	}

	returnVector.push_back(inString.substr(start));
	return returnVector;
}
void getRecursiveDirList(const String& baseDir, StringVec& dirVec, const StringVec& ignoreList)
{ 
  DIR* dir = opendir(baseDir.c_str());
  if (!dir)
    return;
    
  dirVec.push_back(baseDir);

  struct dirent* entry;
  while ((entry = readdir(dir))) {
    if (entry->d_type == DT_DIR) {
      String path = joinPaths(baseDir, entry->d_name);
         
      if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
        continue;
        
      if (matchWildcardList(entry->d_name, ignoreList))
        continue;
      
      getRecursiveDirList(path, dirVec, ignoreList);
    }
  }

  closedir(dir);
}
Example #7
0
inline void setStringVecValue( StringVec& sv, const std::string& value, size_t index = 0 )
{
	size_t size = sv.size();

	if( size <= index )
	{
		while( size < index )
		{
			sv.push_back( "" );
			++size;
		}
		sv.push_back( value );
	}
	else
		sv[index] = value;
}
Example #8
0
StringVec SpeckleyElements::getMeshNames() const
{
    StringVec res;
    if (nodeMesh)
        res.push_back(nodeMesh->getName());
    return res;
}
Example #9
0
ProfileDlg::StringVec ProfileDlg::GetExistingProfiles()
{
	StringVec profiles;
	HKEY hKey;
	if (::RegOpenKeyEx(HKEY_CURRENT_USER, PROFILES_LOC, 0, KEY_READ, &hKey) != ERROR_SUCCESS)
		return profiles;
	
	DWORD dwIndex = 0;
	LONG lRet;
	DWORD len = 50;
	TCHAR profileName[50];

	while ((lRet = ::RegEnumKeyEx(hKey, dwIndex, profileName, &len, NULL,
	NULL, NULL, NULL)) != ERROR_NO_MORE_ITEMS)
	{
		// Do we have a key to open?
		if (lRet == ERROR_SUCCESS)
		{
			// Open the key and get the value
			HKEY hItem;
			if (::RegOpenKeyEx(hKey, profileName, 0, KEY_READ, &hItem) != ERROR_SUCCESS)
				continue;
			profiles.push_back(profileName);
			::RegCloseKey(hItem);
		}
		dwIndex++;
		len = 50;
	}
	::RegCloseKey(hKey);
	return profiles;
}
Example #10
0
  std::string Path::normalize(const std::string & path)
  {
    // Easiest way is: split, then remove "." and remove a/.. (but not ../.. !)
    // This does not get a/b/../.. so if we remove a/.., go through the string again
    // Also need to treat rootdir/.. specially
    // Also normalize(foo/..) -> "." but normalize(foo/bar/..) -> "foo"
    StringVec v = Path::split(path);
    if (v.size() == 0) 
      return "";

    StringVec outv;
    bool doAgain = true;
    while (doAgain) 
    {
      doAgain = false;
      for (unsigned int i = 0; i < v.size(); i++) 
      {
        if (v[i] == "") continue; // remove empty fields
        if (v[i] == "." && v.size() > 1) continue; // skip "." unless it is by itself
        if (i == 0 && isRootdir(v[i]) && i+1 < v.size() && v[i+1] == "..") 
        {
          // <root>/.. -> <root>
          outv.push_back(v[i]);
          i++; // skipped following ".."
          doAgain = true;
          continue;
        }
        // remove "foo/.."
        if (i+1 < v.size() && v[i] != ".." && v[i+1] == "..")
        {
          // but as a special case, if the full path is "foo/.." return "."
          if (v.size() == 2) return ".";
          i++;
          doAgain = true;
          continue;
        }
        outv.push_back(v[i]);
      }
      if (doAgain) 
      {
        v = outv;
        outv.clear();
      }
    }
    return Path::join(outv.begin(), outv.end());

  }
Example #11
0
StringVec explodeString(const std::string& string, const std::string& separator, bool trim/* = true*/)
{
	StringVec returnVector;
	size_t start = 0, end = 0;
	while((end = string.find(separator, start)) != std::string::npos)
	{
		std::string t = string.substr(start, end - start);
		if(trim)
			trimString(t);

		returnVector.push_back(t);
		start = end + separator.size();
	}

	returnVector.push_back(string.substr(start));
	return returnVector;
}
Example #12
0
StringVec Grammar::get_vocab_names() const
{
    StringVec vec;
    if( m_inherit ) {
        vec = m_inherit->get_vocab_names();
    }
    for( size_t i = 0 ; i < m_vocabs.size() ; i++ ) {
        vec.push_back( m_vocabs[i]->get_name() );
    }
    return vec;
}
Example #13
0
//---------------------------------------------------------------------------------------------------------------------
// This is basically like the Perl split() function.  It splits str into substrings by cutting it at each delimiter.  
// The result is stored in vec.
//---------------------------------------------------------------------------------------------------------------------
void Split(const string& str, StringVec& vec, char delimiter)
{
	vec.clear();
	size_t strLen = str.size();
	if (strLen == 0)
		return;

	size_t startIndex = 0;
	size_t indexOfDel = str.find_first_of(delimiter, startIndex);
	while (indexOfDel != string::npos)
	{
		vec.push_back(str.substr(startIndex, indexOfDel-startIndex));
		startIndex=indexOfDel + 1;
		if (startIndex >= strLen)
			break;
		indexOfDel = str.find_first_of(delimiter, startIndex);
	}
	if(startIndex < strLen)
		vec.push_back(str.substr(startIndex));
}
Example #14
0
 int split(StringVec &result, const String &src, const String& delm)
 {
     String _src(src);
     char *p = strtok((char*)_src.c_str(), delm.c_str());
     while (p != NULL)
     {
         result.push_back(p);
         p = strtok(NULL, delm.c_str());
     }
     return int(result.size());
 }
Example #15
0
StringVec Value::as_stringlist() const {
  assert(!is_null() && (value_type() == CASS_VALUE_TYPE_LIST ||
                        value_type() == CASS_VALUE_TYPE_SET) &&
         primary_value_type() == CASS_VALUE_TYPE_VARCHAR);
  StringVec stringlist;
  CollectionIterator iterator(this);
  while (iterator.next()) {
    stringlist.push_back(iterator.value()->to_string());
  }
  return stringlist;
}
Example #16
0
// "Expand" -Wl and -Xlinker tokens
// This is OK to do since we're interested in a small subset of flags.
// Preserving correctness is not important.
static void replaceWlArgs(const StringVec& inArgs, StringVec& outArgs) {
    for (auto arg : inArgs) {
        if (strBeginsWith(arg, "-Wl,")) {
            StringVec tokens;
            tokenize(arg, tokens, ",", "", "", "", "");
            outArgs.insert(outArgs.end(), tokens.begin() + 1, tokens.end());
        } else if (arg != "-Xlinker") {
            outArgs.push_back(arg);
        }
    }
}
Example #17
0
StringVec Buffers::getActive() const
{
	StringVec ret;

	for(unsigned int i = 0; i < Buffers::MaxBuffers; ++i)
	{
		if(m_active[i])
			ret.push_back(std::to_string(i));
	}

	return ret;
}
Example #18
0
StringVec explodeString(const std::string& string, const std::string& separator, bool trim/* = true*/, uint16_t limit/* = 0*/)
{
	StringVec returnVector;
	size_t start = 0, end = 0;

	uint16_t i = 1;
	while((end = string.find(separator, start)) != std::string::npos)
	{
		std::string t = string.substr(start, end - start);
		if(trim)
			trimString(t);

		returnVector.push_back(t);
		start = end + separator.size();

		++i;
		if(limit > 0 && i > limit)
			break;
	}

	returnVector.push_back(string.substr(start));
	return returnVector;
}
Example #19
0
StringVec recDb::GetAttachedDbList()
{
    wxSQLite3ResultSet result =
        s_db->ExecuteQuery( "PRAGMA database_list;" );

    StringVec vec;
    while ( result.NextRow() ) {
        wxString name = result.GetAsString( 1 );
        if ( name == "main" ) {
            continue;
        }
        vec.push_back( name );
    }
    return vec;
}
Example #20
0
  // lookup the string in the map and insert if not there
  long str2index(const std::string & str)
  {
    StringMap::iterator it = m_map.find(&str);

    if (it != m_map.end()) {
      return it->second;
    }

    // add string to table
    const std::string *copy = new std::string(str);
    m_vec.push_back(copy);
    long index = m_vec.size() - 1;
    m_map[copy] = index;

    return index;
  }
Example #21
0
	StringVec Split(std::string str, std::string pattern)
	{
		std::string::size_type pos;
		StringVec result;
		str += pattern;
		int size = str.size();

		for (int i = 0; i < size; i++)
		{
			pos = str.find(pattern, i);
			if (pos < size)
			{
				std::string s = str.substr(i, pos - i);
				result.push_back(s);
				i = pos + pattern.size() - 1;
			}
		}
		return result;
	}
Example #22
0
const std::tuple<bool, std::string, StringVec> proc_tags(const std::string& tags) {
	bool suggest = false;
	std::string errtype;
	StringVec gentags;
	for(auto& tag : split(tags)) {
		std::match_results<const char*> result;
		std::regex_match(tag.c_str(), result, CG_SKIP_TAG);
		if (result.empty()) {
			gentags.push_back(tag);
		}
		else if(result[2].length() != 0) {
			if(tag == CG_SUGGEST_TAG) {
				suggest = true;
			}
			else {
				errtype = result[2];
			}
		}
	}
	return std::make_tuple(suggest, errtype, gentags);
}
void SBFrameworksBuildPhase::writeVCProjectFiles(VCProject& proj) const
{
  // We don't support linking with frameworks when building bundles
  TargetProductType productType = m_parentTarget.getProductType();
  if (productType == TargetBundle) {
    if (!m_phase->getBuildFileList().empty()) {
      SBLog::warning() << "Ignoring all frameworkss in \"" << m_parentTarget.getName() << "\" bundle target." << std::endl;
    }
    return;
  }

  String linkTarget;
  if (productType == TargetApplication)
    linkTarget = "Link";
  else if (productType == TargetStaticLib)
    linkTarget = "Lib";

  // Get paths to all the build files (frameworks)
  StringVec buildFilePaths;
  if (m_phase) {
    const BuildFileList& buildFiles = m_phase->getBuildFileList();
    sbAssert(buildFiles.size() == m_buildFileTargets.size());
    for (size_t i = 0; i < buildFiles.size(); i++) {
      const PBXFile* file = buildFiles[i]->getFile();
      // Ignore any frameworks build from source (they will be added as project references)
      if (file && !m_buildFileTargets[i])
        buildFilePaths.push_back(file->getFullPath());
    }
  }

  for (auto bs : m_parentTarget.getBuildSettings()) {
    VCProjectConfiguration* config = proj.addConfiguration(bs.first);

    // Extrace libs/frameworks from OTHER_LDFLAGS
    StringVec buildFilePaths(buildFilePaths);
    processLDFlags(bs.second->getValue("OTHER_LDFLAGS"), buildFilePaths);

    // Construct a list of libraries to link against
    StringSet linkedLibs;
    linkedLibs.insert("%(AdditionalDependencies)");
    for (auto filePath : buildFilePaths) {
      if (productType == TargetStaticLib && !strEndsWith(filePath, ".a"))
        continue;

      String winLibName = sb_fname(sb_basename(filePath)) + ".lib";

      // If the library is blocked then add the replacement library to our additional dependencies 
      auto it = s_blockedLibraries.find(winLibName);
      while (it != s_blockedLibraries.end())
      {
          // get the replacement library.
          winLibName = it->second;

          // follow any transitive replacement.
          it = s_blockedLibraries.find(winLibName);
      }

      if (!winLibName.empty())
      {
          linkedLibs.insert(winLibName);
      }
    }

    // AdditionalDependencies
    String additionalDeps = joinStrings(linkedLibs, ";");
    if (!additionalDeps.empty()) {
      config->setItemDefinition(linkTarget, "AdditionalDependencies", additionalDeps);
    }
  }
}
Example #24
0
malValuePtr EVAL(malValuePtr ast, malEnvPtr env)
{
    while (1) {
        const malList* list = DYNAMIC_CAST(malList, ast);
        if (!list || (list->count() == 0)) {
            return ast->eval(env);
        }

        // From here on down we are evaluating a non-empty list.
        // First handle the special forms.
        if (const malSymbol* symbol = DYNAMIC_CAST(malSymbol, list->item(0))) {
            String special = symbol->value();
            int argCount = list->count() - 1;

            if (special == "def!") {
                checkArgsIs("def!", 2, argCount);
                const malSymbol* id = VALUE_CAST(malSymbol, list->item(1));
                return env->set(id->value(), EVAL(list->item(2), env));
            }

            if (special == "do") {
                checkArgsAtLeast("do", 1, argCount);

                for (int i = 1; i < argCount; i++) {
                    EVAL(list->item(i), env);
                }
                ast = list->item(argCount);
                continue; // TCO
            }

            if (special == "fn*") {
                checkArgsIs("fn*", 2, argCount);

                const malSequence* bindings =
                    VALUE_CAST(malSequence, list->item(1));
                StringVec params;
                for (int i = 0; i < bindings->count(); i++) {
                    const malSymbol* sym =
                        VALUE_CAST(malSymbol, bindings->item(i));
                    params.push_back(sym->value());
                }

                return mal::lambda(params, list->item(2), env);
            }

            if (special == "if") {
                checkArgsBetween("if", 2, 3, argCount);

                bool isTrue = EVAL(list->item(1), env)->isTrue();
                if (!isTrue && (argCount == 2)) {
                    return mal::nilValue();
                }
                ast = list->item(isTrue ? 2 : 3);
                continue; // TCO
            }

            if (special == "let*") {
                checkArgsIs("let*", 2, argCount);
                const malSequence* bindings =
                    VALUE_CAST(malSequence, list->item(1));
                int count = checkArgsEven("let*", bindings->count());
                malEnvPtr inner(new malEnv(env));
                for (int i = 0; i < count; i += 2) {
                    const malSymbol* var =
                        VALUE_CAST(malSymbol, bindings->item(i));
                    inner->set(var->value(), EVAL(bindings->item(i+1), inner));
                }
                ast = list->item(2);
                env = inner;
                continue; // TCO
            }

            if (special == "quasiquote") {
                checkArgsIs("quasiquote", 1, argCount);
                ast = quasiquote(list->item(1));
                continue; // TCO
            }

            if (special == "quote") {
                checkArgsIs("quote", 1, argCount);
                return list->item(1);
            }
        }

        // Now we're left with the case of a regular list to be evaluated.
        std::unique_ptr<malValueVec> items(list->evalItems(env));
        malValuePtr op = items->at(0);
        if (const malLambda* lambda = DYNAMIC_CAST(malLambda, op)) {
            ast = lambda->getBody();
            env = lambda->makeEnv(items->begin()+1, items->end());
            continue; // TCO
        }
        else {
            return APPLY(op, items->begin()+1, items->end(), env);
        }
    }
}
Example #25
0
  Path::StringVec Path::split(const std::string & path)
  {
    /**
     * Don't use boost::tokenizer because we need to handle the prefix specially.
     * Handling the prefix is messy on windows, but this is the only place we have 
     * to do it
     */
    StringVec parts;
    std::string::size_type curpos = 0;
    if (path.size() == 0)
      return parts;

#ifndef WIN32
    // only possible prefix is "/"
    if (path[0] == '/') 
    {
      parts.push_back("/");
      curpos++;
    }
#else
    // prefix may be 1) "\", 2) "\\", 3) "[a-z]:", 4) "[a-z]:\"
    if (path.size() == 1) 
    {
      // captures both "\" and "a"
      parts.push_back(path);
      return parts;
    }
    if (path[0] == '\\') 
    {
      if (path[1] == '\\') 
      {
        // case 2
        parts.push_back("\\\\");
        curpos = 2;
      } 
      else 
      {
        // case 1
        parts.push_back("\\");
        curpos = 1;
      }
    } 
    else 
    {
      if (path[1] == ':') 
      {
        if (path.size() > 2 && path[2] == '\\') 
        {
          // case 4
          parts.push_back(path.substr(0, 3));
          curpos = 3;
        } 
        else 
        {
          parts.push_back(path.substr(0, 2));
          curpos = 2;
        }
      }
    }          
#endif

    // simple tokenization based on separator. Note that "foo//bar" -> "foo", "", "bar"
    std::string::size_type newpos;
    while (curpos < path.size() && curpos != std::string::npos) 
    {
      // Be able to split on either separator including mixed separators on Windows
    #ifdef WIN32
      std::string::size_type p1 = path.find("\\", curpos);
      std::string::size_type p2 = path.find("/", curpos);
      newpos = p1 < p2 ? p1 : p2;
    #else
      newpos = path.find(Path::sep, curpos);
    #endif
    
      if (newpos == std::string::npos) 
      {
        parts.push_back(path.substr(curpos));
        curpos = newpos;
      } 
      else 
      {
        // note: if we have a "//" then newpos == curpos and this string is empty
        if (newpos != curpos) 
        {
          parts.push_back(path.substr(curpos, newpos - curpos));
        }
        curpos = newpos + 1;
      }
    }
    
    return parts;

  }
Example #26
0
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
	QApplication app(argc, argv);

    typedef std::vector<std::string> StringVec;
    namespace po = boost::program_options;
    // optional options
    po::options_description optionsDesc("options");
    optionsDesc.add_options()
        ("help,h", "help message")
        ("stats,s", po::value<int>()->default_value(0),
         "frame statistics verbosity")
        ("threads,t", po::value<int>()->default_value(-1),
         "number of threads to use (-1 = auto)")
        ("opts", po::value<std::string>()->default_value(""),
         "frame render options")
    ;
    // options + positional parameters
    po::options_description allArgs("All arguments");
    allArgs.add(optionsDesc);
    allArgs.add_options()
        ("rib_files", po::value<StringVec>(), "RIB files to render")
    ;
    po::positional_options_description params;
    params.add("rib_files", -1);
    // Parse options
    po::variables_map opts;
    po::store(po::command_line_parser(argc, argv)
              .options(allArgs).positional(params).run(), opts);
    po::notify(opts);

    if(opts.count("help") || opts.count("rib_files") == 0)
    {
        std::cout
            << "Usage: " << argv[0] << " [options] model.rib\n\n"
            << optionsDesc;
        return 0;
    }

    boost::shared_ptr<Ri::RendererServices> renderer(createRenderer());

    // Command line options
    Ri::Renderer& ri = renderer->firstFilter();
    ri.Option("statistics", ParamListBuilder()
              ("endofframe", opts["stats"].as<int>()));
    ri.Option("limits", ParamListBuilder()
              ("threads", opts["threads"].as<int>()));

    // Default hard-coded frame options.
    ri.PixelSamples(2, 2);
    ri.PixelFilter(renderer->getFilterFunc("sinc"), 3, 3);
    ri.ShadingRate(1);
    ri.Option("limits", ParamListBuilder()("eyesplits", 6));
    ri.Clipping(0.3, FLT_MAX);

	// Build a list of all ribFiles specified, expanding wildcards where necessary
	StringVec allFiles;
	const StringVec& ribFiles = opts["rib_files"].as<StringVec>();
	for(StringVec::const_iterator rf = ribFiles.begin(), rfEnd = ribFiles.end(); rf != rfEnd; ++rf)
	{
		std::vector<std::string> files = cliGlob(*rf);
		for(std::vector<std::string>::iterator f = files.begin(), fend = files.end(); f != fend; ++f)
			allFiles.push_back(*f);
	}

    RenderWindow win(640, 480, *renderer, opts["opts"].as<std::string>(),
                     allFiles);

	QObject::connect(&win, SIGNAL(exitApplication()), &app, SLOT(quit()));

    win.show();
	win.adjustSize();

    return app.exec();
}
Example #27
0
malValuePtr EVAL(malValuePtr ast, malEnvPtr env)
{
    if (!env) {
        env = replEnv;
    }
    while (1) {
        const malList* list = DYNAMIC_CAST(malList, ast);
        if (!list || (list->count() == 0)) {
            return ast->eval(env);
        }

        ast = macroExpand(ast, env);
        list = DYNAMIC_CAST(malList, ast);
        if (!list || (list->count() == 0)) {
            return ast->eval(env);
        }

        // From here on down we are evaluating a non-empty list.
        // First handle the special forms.
        if (const malSymbol* symbol = DYNAMIC_CAST(malSymbol, list->item(0))) {
            String special = symbol->value();
            int argCount = list->count() - 1;

            if (special == "def!") {
                checkArgsIs("def!", 2, argCount);
                const malSymbol* id = VALUE_CAST(malSymbol, list->item(1));
                return env->set(id->value(), EVAL(list->item(2), env));
            }

            if (special == "defmacro!") {
                checkArgsIs("defmacro!", 2, argCount);

                const malSymbol* id = VALUE_CAST(malSymbol, list->item(1));
                malValuePtr body = EVAL(list->item(2), env);
                const malLambda* lambda = VALUE_CAST(malLambda, body);
                return env->set(id->value(), mal::macro(*lambda));
            }

            if (special == "do") {
                checkArgsAtLeast("do", 1, argCount);

                for (int i = 1; i < argCount; i++) {
                    EVAL(list->item(i), env);
                }
                ast = list->item(argCount);
                continue; // TCO
            }

            if (special == "fn*") {
                checkArgsIs("fn*", 2, argCount);

                const malSequence* bindings =
                    VALUE_CAST(malSequence, list->item(1));
                StringVec params;
                for (int i = 0; i < bindings->count(); i++) {
                    const malSymbol* sym =
                        VALUE_CAST(malSymbol, bindings->item(i));
                    params.push_back(sym->value());
                }

                return mal::lambda(params, list->item(2), env);
            }

            if (special == "if") {
                checkArgsBetween("if", 2, 3, argCount);

                bool isTrue = EVAL(list->item(1), env)->isTrue();
                if (!isTrue && (argCount == 2)) {
                    return mal::nilValue();
                }
                ast = list->item(isTrue ? 2 : 3);
                continue; // TCO
            }

            if (special == "let*") {
                checkArgsIs("let*", 2, argCount);
                const malSequence* bindings =
                    VALUE_CAST(malSequence, list->item(1));
                int count = checkArgsEven("let*", bindings->count());
                malEnvPtr inner(new malEnv(env));
                for (int i = 0; i < count; i += 2) {
                    const malSymbol* var =
                        VALUE_CAST(malSymbol, bindings->item(i));
                    inner->set(var->value(), EVAL(bindings->item(i+1), inner));
                }
                ast = list->item(2);
                env = inner;
                continue; // TCO
            }

            if (special == "macroexpand") {
                checkArgsIs("macroexpand", 1, argCount);
                return macroExpand(list->item(1), env);
            }

            if (special == "quasiquote") {
                checkArgsIs("quasiquote", 1, argCount);
                ast = quasiquote(list->item(1));
                continue; // TCO
            }

            if (special == "quote") {
                checkArgsIs("quote", 1, argCount);
                return list->item(1);
            }

            if (special == "try*") {
                checkArgsIs("try*", 2, argCount);
                malValuePtr tryBody = list->item(1);
                const malList* catchBlock = VALUE_CAST(malList, list->item(2));

                checkArgsIs("catch*", 2, catchBlock->count() - 1);
                MAL_CHECK(VALUE_CAST(malSymbol,
                    catchBlock->item(0))->value() == "catch*",
                    "catch block must begin with catch*");

                // We don't need excSym at this scope, but we want to check
                // that the catch block is valid always, not just in case of
                // an exception.
                const malSymbol* excSym =
                    VALUE_CAST(malSymbol, catchBlock->item(1));

                malValuePtr excVal;

                try {
                    ast = EVAL(tryBody, env);
                }
                catch(String& s) {
                    excVal = mal::string(s);
                }
                catch (malEmptyInputException&) {
                    // Not an error, continue as if we got nil
                    ast = mal::nilValue();
                }
                catch(malValuePtr& o) {
                    excVal = o;
                };

                if (excVal) {
                    // we got some exception
                    env = malEnvPtr(new malEnv(env));
                    env->set(excSym->value(), excVal);
                    ast = catchBlock->item(2);
                }
                continue; // TCO
            }
        }

        // Now we're left with the case of a regular list to be evaluated.
        std::unique_ptr<malValueVec> items(list->evalItems(env));
        malValuePtr op = items->at(0);
        if (const malLambda* lambda = DYNAMIC_CAST(malLambda, op)) {
            ast = lambda->getBody();
            env = lambda->makeEnv(items->begin()+1, items->end());
            continue; // TCO
        }
        else {
            return APPLY(op, items->begin()+1, items->end());
        }
    }
}
int main( int argc, char *argv[] ) {
	if ( argc < 3 ) {
		std::cout << "Usage: ./compileSHE <domain.pddl> <task.pddl>\n";
		std::cout << "Writes domain file to standard output and instance file to standard error\n";
		exit( 1 );
	}

	d = new Domain( argv[1] );
	ins = new Instance( *d, argv[2] );

	// Generate dependency graph among actions and identify durations and depths

	graph g( d->actions.size() );
	for ( unsigned i = 0; i < d->actions.size(); ++i ) {
		for ( unsigned j = 0; j < d->actions.size(); ++j )
			if ( i != j )
				detectDependency( i, j, g );
	}
	g.computeDurations();
	g.computeDepths();

	// Identify contexts that are threatened by contents
	// RIGHT NOW PRE & EFF ASSUME POSITIVE PRECONDITIONS !!!

	int maxCount = 0;
	for ( unsigned i = 0; i < d->actions.size(); ++i ) {
		maxCount = MAX( maxCount, *g.depths[i].rbegin() );
		for ( unsigned j = 0; j < get( i )->pre_o->conds.size(); ++j ) {
			Ground * pre = dynamic_cast< Ground * >( get( i )->pre_o->conds[j] );
			if ( pre ) {
				int k = d->preds.index( pre->name );
				if ( k >= 0 && isPre( i, k, g ) )
					pres.insert( k );
			}
		}
	}

	// Create classical domain
	cd = new Domain;
	cd->name = d->name;
	cd->equality = d->equality;
	cd->condeffects = cd->typed = true;
	cd->cons = d->cons || ( maxCount && pres.size() ) || g.subtractionPairs.size();
	cd->equality = d->equality;

	// Add types
	cd->setTypes( d->copyTypes() );
	if ( maxCount && pres.size() ) cd->createType( "COUNT" );
	if ( g.subtractionPairs.size() ) cd->createType( "TIME" );

	// Add constants
	StringVec counts;
	for ( int i = 0; maxCount && pres.size() && i <= maxCount; ++i ) {
		std::stringstream ss;
		ss << "COUNT" << i;
		counts.push_back( ss.str() );
		cd->createConstant( counts[i], "COUNT" );
	}
	StringVec times;
	for ( unsigned i = 0; g.subtractionPairs.size() && i < g.durationMap.size(); ++i ) {
		std::stringstream ss;
		ss << "TIME" << i;
		times.push_back( ss.str() );
		cd->createConstant( times[i], "TIME" );
	}

	// Add predicates
	for ( unsigned i = 0; i < d->preds.size(); ++i ) {
		StringVec pars = d->typeList( d->preds[i] );
		cd->createPredicate( d->preds[i]->name, pars );
		if ( pres.find( i ) != pres.end() ) {
			pars.push_back( "COUNT" );
			cd->createPredicate( "COUNT-" + d->preds[i]->name, pars );
		}
	}

	StringVec stacks( 1, "EMPTYSTACK" );
	cd->createPredicate( stacks[0] );
	for ( int i = 1; i <= maxCount; ++i ) {
		std::stringstream ss;
		ss << "STACK" << i;
		stacks.push_back( ss.str() );
		cd->createPredicate( stacks[i] );
		cd->createPredicate( stacks[i] + "-REMAINING", StringVec( 1, "TIME" ) );
		cd->createPredicate( stacks[i] + "-INCREASE", StringVec( 1, "TIME" ) );
		cd->createPredicate( stacks[i] + "-DECREASE" );
		cd->createPredicate( stacks[i] + "-CONTINUE", StringVec( 1, "TIME" ) );
	}

	for ( unsigned i = 0; i < d->actions.size(); ++i )
		for ( IntSet::iterator j = g.depths[i].begin(); g.outgoing( i ) && j != g.depths[i].end(); ++j ) {
			std::stringstream ss;
			ss << "STACK" << *j + 1 << "-" << d->actions[i]->name;
			cd->createPredicate( ss.str(), d->typeList( d->actions[i] ) );
		}

	if ( counts.size() )
		cd->createPredicate( "CONSECUTIVE", StringVec( 2, "COUNT" ) );

	if ( times.size() )
		cd->createPredicate( "SUBTRACT", StringVec( 3, "TIME" ) );

	// Currently does NOT add functions
//	for ( unsigned i = 0; i < d->funcs.size(); ++i )
//		cd->createFunction( d->funcs[i]->name, d->funcs[i]->returnType, d->typeList( d->funcs[i] ) );

	// Add actions
	for ( unsigned i = 0; i < d->actions.size(); ++i )
		// DOES NOT CURRENTLY IMPLEMENT COUNT MECHANISM !!!
		for ( IntSet::iterator j = g.depths[i].begin(); j != g.depths[i].end(); ++j )
			if ( g.outgoing( i ) ) {
				// Action is an envelope: compile into push and pop action

				// Push action
				std::string name = "PUSH-" + d->actions[i]->name;
				unsigned size = d->actions[i]->params.size();
				Action * push = cd->createAction( name, d->typeList( d->actions[i] ) );

				//std::cout << "Creating action " << name << "\n";

				// ONLY DEALS WITH POSITIVE PRECONDITIONS HERE !!!
				cd->setPre( name, d->actions[i]->pre );
				for ( unsigned k = 0; k < get( i )->pre_o->conds.size(); ++k ) {
					Ground * pre = dynamic_cast< Ground * >( get( i )->pre_o->conds[k] );
					if ( pre && !includes( 0, pre, ( And * )get( i )->pre ) &&
					            !includes( 0, pre, ( And * )get( i )->eff ) )
						cd->addPre( 0, name, pre->name, pre->params );
					// if precon is not positive, just copy it
					if ( !pre ) ( ( And * )push->pre )->add( get( i )->pre_o->conds[k]->copy( *cd ) );
				}
				cd->addPre( 0, name, stacks[*j] );

				cd->setEff( name, d->actions[i]->eff );
				cd->addEff( 1, name, stacks[*j] );
				if ( *j ) cd->addEff( 0, name, stacks[*j] + "-INCREASE", IntVec( 1, cd->constantIndex( times[g.durationMap[d->actions[i]->duration()]], "TIME" ) ) );
				else cd->addEff( 0, name, stacks[1] );
				cd->addEff( 0, name, stacks[*j + 1] + "-" + d->actions[i]->name, incvec( 0, size ) );
				cd->addEff( 0, name, stacks[*j + 1] + "-REMAINING", IntVec( 1, cd->constantIndex( times[g.durationMap[d->actions[i]->duration()]], "TIME" ) ) );

				// Pop action
				name = "POP-" + d->actions[i]->name;
				cd->createAction( name, d->typeList( d->actions[i] ) );

				//std::cout << "Creating action " << name << "\n";

				// ONLY DEALS WITH POSITIVE PRECONDITIONS HERE !!!
				cd->setPre( name, get( i )->pre_e );
				for ( unsigned k = 0; k < get( i )->pre_o->conds.size(); ++k ) {
					Ground * h = dynamic_cast< Ground * >( get( i )->pre_o->conds[k] );
					if ( h && !includes( 0, h, get( i )->pre_e ) )
						cd->addPre( 0, name, h->name, h->params );
				}
				cd->addPre( 0, name, stacks[*j + 1] );
				cd->addPre( 0, name, stacks[*j + 1] + "-" + d->actions[i]->name, incvec( 0, size ) );

				cd->setEff( name, get( i )->eff_e );
				cd->addEff( 0, name, stacks[*j + 1] + "-DECREASE" );
				cd->addEff( 1, name, stacks[*j + 1] );
				cd->addEff( 1, name, stacks[*j + 1] + "-" + d->actions[i]->name, incvec( 0, size ) );
			}
			else {
				// Action is not an envelope: compile into compressed action
				std::string name = "DO-" + d->actions[i]->name;
				Action * doit = cd->createAction( name, d->typeList( d->actions[i] ) );

				//std::cout << "Creating action " << name << "\n";

				// ONLY DEALS WITH POSITIVE PRECONDITIONS HERE !!!
				cd->setPre( name, d->actions[i]->pre );
				for ( unsigned k = 0; k < get( i )->pre_o->conds.size(); ++k ) {
					Ground * pre = dynamic_cast< Ground * >( get( i )->pre_o->conds[k] );
					if ( pre && !includes( 0, pre, ( And * )get( i )->pre ) &&
					            !includes( 0, pre, ( And * )get( i )->eff ) )
						cd->addPre( 0, name, pre->name, pre->params );
					// if precon is not positive, just copy it
					if ( !pre ) ( ( And * )doit->pre )->add( get( i )->pre_o->conds[k]->copy( *cd ) );
				}
				for ( unsigned k = 0; k < get( i )->pre_e->conds.size(); ++k ) {
					Ground * h = ( Ground * )get( i )->pre_e->conds[k];
					if ( !includes( 0, h, ( And * )get( i )->pre ) &&
					     !includes( 0, h, ( And * )get( i )->eff ) )
						cd->addPre( 0, name, h->name, h->params );
				}
				cd->addPre( 0, name, stacks[*j] );

				cd->setEff( name, get( i )->eff_e );
				GroundVec add = get( i )->addEffects();
				for ( unsigned k = 0; k < add.size(); ++k )
					if ( !includes( 1, add[k], get( i )->eff_e ) )
						cd->addEff( 0, name, add[k]->name, add[k]->params );
				GroundVec del = get( i )->deleteEffects();
				for ( unsigned k = 0; k < del.size(); ++k )
					if ( !includes( 0, del[k], get( i )->eff_e ) )
						cd->addEff( 1, name, del[k]->name, del[k]->params );
				if ( *j ) {
					cd->addEff( 1, name, stacks[*j] );
					cd->addEff( 0, name, stacks[*j] + "-CONTINUE", IntVec( 1, cd->constantIndex( times[g.durationMap[d->actions[i]->duration()]], "TIME" ) ) );
				}
			}

	for ( int i = 1; i <= maxCount; ++i ) {
		if ( i < maxCount ) {
			// Increase action
			std::stringstream ss;
			ss << "INCREASE" << i;
			std::string name = ss.str();
			cd->createAction( name, StringVec( 3, "TIME" ) );

			cd->addPre( 0, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
			cd->addPre( 0, name, stacks[i] + "-INCREASE", incvec( 2, 3 ) );
			cd->addPre( 0, name, "SUBTRACT", incvec( 0, 3 ) );

			cd->addEff( 0, name, stacks[i + 1] );
			cd->addEff( 1, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
			cd->addEff( 0, name, stacks[i] + "-REMAINING", incvec( 1, 2 ) );
			cd->addEff( 1, name, stacks[i] + "-INCREASE", incvec( 2, 3 ) );
		}
		
		// Decrease action
		std::stringstream ss;
		ss << "DECREASE" << i;
		std::string name = ss.str();
		cd->createAction( name, StringVec( 1, "TIME" ) );

		cd->addPre( 0, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
		cd->addPre( 0, name, stacks[i] + "-DECREASE" );

		cd->addEff( 0, name, stacks[i - 1] );
		cd->addEff( 1, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
		cd->addEff( 1, name, stacks[i] + "-DECREASE" );

		// Continue action
		std::stringstream ss2;
		ss2 << "CONTINUE" << i;
		name = ss2.str();
		cd->createAction( name, StringVec( 3, "TIME" ) );

		cd->addPre( 0, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
		cd->addPre( 0, name, stacks[i] + "-CONTINUE", incvec( 2, 3 ) );
		cd->addPre( 0, name, "SUBTRACT", incvec( 0, 3 ) );
		
		cd->addEff( 0, name, stacks[i] );
		cd->addEff( 1, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
		cd->addEff( 0, name, stacks[i] + "-REMAINING", incvec( 1, 2 ) );
		cd->addEff( 1, name, stacks[i] + "-CONTINUE", incvec( 2, 3 ) );
	}

	cd->PDDLPrint( std::cout );

	cins = new Instance( *cd );
	cins->name = ins->name;

	// create initial state
	for ( unsigned i = 0; i < ins->init.size(); ++i )
		if ( d->preds.index( ins->init[i]->name ) >= 0 )
			cins->addInit( ins->init[i]->name, d->objectList( ins->init[i] ) );
	cins->addInit( stacks[0] );

	for ( unsigned i = 1; i < counts.size(); ++i ) {
		StringVec pars( 1, counts[i - 1] );
		pars.push_back( counts[i] );
		cins->addInit( "CONSECUTIVE", pars );
	}
	for ( DoublePairSet::iterator i = g.subtractionPairs.begin(); i != g.subtractionPairs.end(); ++i ) {
		StringVec pars( 1, times[g.durationMap[i->first]] );
		pars.push_back( times[g.durationMap[i->first - i->second]] );
		pars.push_back( times[g.durationMap[i->second]] );
		cins->addInit( "SUBTRACT", pars );
	}

	// create goal state
	for ( unsigned i = 0; i < ins->goal.size(); ++i )
		cins->addGoal( ins->goal[i]->name, d->objectList( ins->goal[i] ) );
	cins->addGoal( stacks[0] );

	cins->PDDLPrint( std::cerr );

	delete cins;
	delete cd;
	delete ins;
	delete d;
}
Example #29
0
Variant c_DebuggerClient::t_processcmd(CVarRef cmdName, CVarRef args) {
  INSTANCE_METHOD_INJECTION_BUILTIN(DebuggerClient, DebuggerClient::processcmd);
  if (!m_client ||
      m_client->getClientState() < DebuggerClient::StateReadyForCommand) {
    raise_warning("client is not initialized");
    return null;
  }
  if (m_client->getClientState() != DebuggerClient::StateReadyForCommand) {
    raise_warning("client is not ready to take command");
    return null;
  }
  if (!cmdName.isString()) {
    raise_warning("cmdName must be string");
    return null;
  }
  if (!args.isNull() && !args.isArray()) {
    raise_warning("args must be null or array");
    return null;
  }

  static const char *s_allowedCmds[] = {
    "break", "continue", "down", "exception", "frame", "global",
    "help", "info", "konstant", "next", "out", "print", "quit", "step",
    "up", "variable", "where", "bt", "set", "inst", "=", "@", NULL
  };

  bool allowed = false;
  for (int i = 0; ; i++) {
    const char *cmd = s_allowedCmds[i];
    if (cmd == NULL) {
      break;
    }
    if (cmdName.same(cmd)) {
      allowed = true;
      break;
    }
  }
  if (!allowed) {
    raise_warning("unsupported command %s", cmdName.toString().data());
    return null;
  }

  m_client->setCommand(cmdName.toString().data());
  StringVec *clientArgs = m_client->args();
  clientArgs->clear();
  if (!args.isNull()) {
    for (ArrayIter iter(args.toArray()); iter; ++iter) {
      CStrRef arg = iter.second().toString();
      clientArgs->push_back(std::string(arg.data(), arg.size()));
    }
  }
  try {
    if (!m_client->process()) {
      raise_warning("command \"%s\" not found", cmdName.toString().data());
    }
  } catch (DebuggerConsoleExitException &e) {
    // Flow-control command goes here
    Logger::Info("wait for debugger client to stop");
    m_client->setTakingInterrupt();
    m_client->setClientState(DebuggerClient::StateBusy);
    DebuggerCommandPtr cmd = m_client->waitForNextInterrupt();
    if (!cmd) {
      raise_warning("not getting a command");
    } else if (cmd->is(DebuggerCommand::KindOfInterrupt)) {
      CmdInterruptPtr cmdInterrupt = dynamic_pointer_cast<CmdInterrupt>(cmd);
      cmdInterrupt->onClientD(m_client);
    } else {
      // Previous pending commands
      cmd->handleReply(m_client);
      cmd->setClientOutput(m_client);
    }
    Logger::Info("debugger client ready for command");
  } catch (DebuggerClientExitException &e) {
    const std::string& nameStr = m_client->getNameApi();
    Logger::Info("client %s disconnected", nameStr.c_str());
    s_dbgCltMap.erase(nameStr);
    delete m_client;
    m_client = NULL;
    return true;
  } catch (DebuggerProtocolException &e) {
    raise_warning("DebuggerProtocolException");
    return null;
  }

  return m_client->getOutputArray();
}
Example #30
0
bool parseVocationNode(xmlNodePtr vocationNode, VocationMap& vocationMap, StringVec& vocStringVec, std::string& errorStr)
{
	if(xmlStrcmp(vocationNode->name,(const xmlChar*)"vocation"))
		return true;

	int32_t vocationId = -1;
	std::string strValue, tmpStrValue;
	if(readXMLString(vocationNode, "name", strValue))
	{
		vocationId = Vocations::getInstance()->getVocationId(strValue);
		if(vocationId != -1)
		{
			vocationMap[vocationId] = true;
			int32_t promotedVocation = Vocations::getInstance()->getPromotedVocation(vocationId);
			if(promotedVocation != -1)
				vocationMap[promotedVocation] = true;
		}
		else
		{
			errorStr = "Wrong vocation name: " + strValue;
			return false;
		}
	}
	else if(readXMLString(vocationNode, "id", strValue))
	{
		IntegerVec intVector;
		if(!parseIntegerVec(strValue, intVector))
		{
			errorStr = "Invalid vocation id - '" + strValue + "'";
			return false;
		}

		size_t size = intVector.size();
		for(size_t i = 0; i < size; ++i)
		{
			Vocation* vocation = Vocations::getInstance()->getVocation(intVector[i]);
			if(vocation && vocation->getName() != "")
			{
				vocationId = vocation->getId();
				strValue = vocation->getName();

				vocationMap[vocationId] = true;
				int32_t promotedVocation = Vocations::getInstance()->getPromotedVocation(vocationId);
				if(promotedVocation != -1)
					vocationMap[promotedVocation] = true;
			}
			else
			{
				std::stringstream ss;
				ss << "Wrong vocation id: " << intVector[i];

				errorStr = ss.str();
				return false;
			}
		}
	}

	if(vocationId != -1 && (!readXMLString(vocationNode, "showInDescription", tmpStrValue) || booleanString(tmpStrValue)))
		vocStringVec.push_back(asLowerCaseString(strValue));

	return true;
}