Beispiel #1
0
bool
inWordSet(int i)
{
  const ECString& w = Pst::fromInt(i);
  if(wordSet.find(w) == wordSet.end()) return false;
  return true;
}
Beispiel #2
0
static bool has_repeats(const Fragments& fragments) {
    StringSet genomes;
    BOOST_FOREACH (Fragment* f, fragments) {
        ASSERT_TRUE(f->seq());
        std::string genome = f->seq()->genome();
        if (genomes.find(genome) != genomes.end()) {
            return true;
        }
        genomes.insert(genome);
    }
Beispiel #3
0
// Note: static method
bool LDModelParser::unsetToken(StringSet &tokens, const char *token)
{
	StringSet::iterator it = tokens.find(token);

	if (it != tokens.end())
	{
		tokens.erase(it);
		return true;
	}
	return false;
}
bool SemanticValidator::nameIsUnique(StringSet set, const std::string name, CdefMessage msgType, const std::string& property)
{
	StringSet::const_iterator got = set.find(name);

	if (got != set.end()) {
		CompileMessage error(CompileMessage::type_t::Error, msgType, _callback, 
			"The %s '%s' is used more than once", property.c_str(), name.c_str());
		return false;
	}

	set.insert(name);
	return true;
}
void PointMatcher<T>::ICPChainBase::loadFromYaml(std::istream& in)
{
	this->cleanup();
	
	YAML::Parser parser(in);
	YAML::Node doc;
	parser.GetNextDocument(doc);
	typedef set<string> StringSet;
	StringSet usedModuleTypes;
	
	// Fix for issue #6: compilation on gcc 4.4.4
	//PointMatcher<T> pm;
	const PointMatcher & pm = PointMatcher::get();

	{
		// NOTE: The logger needs to be initialize first to allow ouput from other contructors
		boost::mutex::scoped_lock lock(loggerMutex);
		usedModuleTypes.insert(createModuleFromRegistrar("logger", doc, pm.REG(Logger), logger));
	}
	usedModuleTypes.insert(createModulesFromRegistrar("readingDataPointsFilters", doc, pm.REG(DataPointsFilter), readingDataPointsFilters));
	usedModuleTypes.insert(createModulesFromRegistrar("readingStepDataPointsFilters", doc, pm.REG(DataPointsFilter), readingStepDataPointsFilters));
	usedModuleTypes.insert(createModulesFromRegistrar("referenceDataPointsFilters", doc, pm.REG(DataPointsFilter), referenceDataPointsFilters));
	//usedModuleTypes.insert(createModulesFromRegistrar("transformations", doc, pm.REG(Transformation), transformations));
	//usedModuleTypes.insert(createModuleFromRegistrar("matcher", doc, pm.REG(Matcher), matcher)); // don't destroy the already created tree
	usedModuleTypes.insert(createModulesFromRegistrar("outlierFilters", doc, pm.REG(OutlierFilter), outlierFilters));
	usedModuleTypes.insert(createModuleFromRegistrar("errorMinimizer", doc, pm.REG(ErrorMinimizer), errorMinimizer));

	// See if to use a rigid transformation
	if (nodeVal("errorMinimizer", doc) != "PointToPointSimilarityErrorMinimizer")
		this->transformations.push_back(new typename TransformationsImpl<T>::RigidTransformation());
	else
		this->transformations.push_back(new typename TransformationsImpl<T>::SimilarityTransformation());
	
	usedModuleTypes.insert(createModulesFromRegistrar("transformationCheckers", doc, pm.REG(TransformationChecker), transformationCheckers));
	usedModuleTypes.insert(createModuleFromRegistrar("inspector", doc, pm.REG(Inspector),inspector));
	
	
	// FIXME: this line cause segfault when there is an error in the yaml file...
	//loadAdditionalYAMLContent(doc);
	
	// check YAML entries that do not correspend to any module
	for(YAML::Iterator moduleTypeIt = doc.begin(); moduleTypeIt != doc.end(); ++moduleTypeIt)
	{
		string moduleType;
		moduleTypeIt.first() >> moduleType;
		if (moduleType != "matcher" && usedModuleTypes.find(moduleType) == usedModuleTypes.end())
			throw InvalidModuleType(
				(boost::format("Module type %1% does not exist") % moduleType).str()
			);
	}
}
Beispiel #6
0
	bool IsBoolField(const string& field_name) {
		static StringSet int_bool_filter, special_bool_filter;
		if (int_bool_filter.empty() && special_bool_filter.empty()) {
			int_bool_filter.insert("lan-mode");
			int_bool_filter.insert("announce");
			int_bool_filter.insert("query");
			int_bool_filter.insert("rcon");
			int_bool_filter.insert("logqueries");
			int_bool_filter.insert("chatlogging");

			special_bool_filter.insert("timestamp");
			special_bool_filter.insert("output");
		}
		return int_bool_filter.end() != int_bool_filter.find(field_name) || special_bool_filter.end() != special_bool_filter.find(field_name);
	}
Beispiel #7
0
 int MMKVImpl::SIsMember(DBID db, const Data& key, const Data& member)
 {
     int err = 0;
     RWLockGuard<MemorySegmentManager, READ_LOCK> keylock_guard(m_segment);
     StringSet* set = GetObject<StringSet>(db, key, V_TYPE_SET, false, err)();
     if (IS_NOT_EXISTS(err))
     {
         return 0;
     }
     if (NULL == set || 0 != err)
     {
         return err;
     }
     return set->find(Object(member, true)) != set->end();
 }
Beispiel #8
0
static bool can_finalize_function(StringRef F, SmallSet<Module*, 16> &known)
{
    if (incomplete_fname.find(F) != incomplete_fname.end())
        return false;
    Module *M = module_for_fname.lookup(F);
    if (M && known.insert(M).second) {
        for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
            Function *F = &*I;
            if (F->isDeclaration() && !isIntrinsicFunction(F)) {
                if (!can_finalize_function(F->getName(), known))
                    return false;
            }
        }
    }
    return true;
}
void reportingFrequencyGeneralTests(SqlFile& file, const SqlFileTimeSeriesQueryVector& allQueries) {
  // list of reporting frequencies from file should match .valueDescriptions() from vector
  StringSet rfStrs;
  for (const std::string& envPeriod : file.availableEnvPeriods()) {
    StringVector rfStrsForEnv = file.availableReportingFrequencies(envPeriod);
    rfStrs.insert(rfStrsForEnv.begin(),rfStrsForEnv.end());
  }
  ReportingFrequencySet rfSetFromVector = reportingFrequencies(allQueries);
  StringSet rfStrsFromVector;
  for (const ReportingFrequency& rf : rfSetFromVector) {
    rfStrsFromVector.insert(rf.valueDescription());
  }
  EXPECT_TRUE(rfStrs.size() >= rfStrsFromVector.size());
  for (const std::string& rfStr : rfStrsFromVector) {
    EXPECT_TRUE(rfStrs.find(rfStr) != rfStrs.end());
  }
}
int main() {
    StringSet strings = SourceHighlightUtils::getFileNames(BASEDIR, "lang");

    printStringSet(strings);
    cout << endl;

    assertTrue(strings.find("java.lang") != strings.end(), "expected java.lang");
    assertTrue(strings.find("symbols.lang") != strings.end(),
            "expected symbols.lang");
    assertTrue(strings.find("foobar.lang") == strings.end(),
            "NON expected foobar.lang");

    strings = SourceHighlightUtils::getStyleFileNames(BASEDIR);

    printStringSet(strings);
    cout << endl;

    assertTrue(strings.find("default.style") != strings.end(),
            "expected default.style");

    strings = SourceHighlightUtils::getCssStyleFileNames(BASEDIR);

    printStringSet(strings);
    cout << endl;

    assertTrue(strings.find("default.css") != strings.end(),
                "expected default.css");

    strings = SourceHighlightUtils::getLangFileNames(BASEDIR);

    printStringSet(strings);
    cout << endl;

    assertTrue(strings.find("java.lang") != strings.end(),
                "expected java.lang");

    strings = SourceHighlightUtils::getOutLangFileNames(BASEDIR);

    printStringSet(strings);
    cout << endl;

    assertTrue(strings.find("html.outlang") != strings.end(),
                "expected html.outlang");

    cout << "test_utils: SUCCESS" << endl;

    return 0;
}
Beispiel #11
0
	void ConvertToBool(string& field_name) {
		static StringSet special_bool_filter;
		if(special_bool_filter.empty()) {
			special_bool_filter.insert("timestamp");
			special_bool_filter.insert("output");
		}
		if(special_bool_filter.end() == special_bool_filter.find(field_name)) {
			if("on" == m_conf[field_name])
				m_conf[field_name] = "1";
			else
				m_conf[field_name] = "0";
		} else {
			if("on" == m_conf[field_name])
				m_conf[field_name] = "Enable";
			else
				m_conf[field_name] = "Disable";
		}
	}
  static void verifyAndReportDangerousProperties(const StringSet &dangerousProperties,
                                                 const StringSet &clearedProperties,
                                                 const std::string &ivarName,
                                                 const QualType ivarType,
                                                 const std::string &declName,
                                                 const std::function<void(StringRef)> &emitBugReport) {
    // Verify that all the dangerous properties have been cleared
    for(auto it = dangerousProperties.begin(), end = dangerousProperties.end(); it != end; it++) {

      if (clearedProperties.find(*it) == clearedProperties.end()) {
        llvm::SmallString<128> buf;
        llvm::raw_svector_ostream os(buf);
        StringRef className;
        const ObjCObjectPointerType *classType = dyn_cast_or_null<ObjCObjectPointerType>(ivarType.getTypePtr());
        if (classType && classType->getInterfaceDecl()) {
          className = classType->getInterfaceDecl()->getName();
        }

        os << "Leaking unsafe reference to self stored in "<< ivarName << "." << *it;
        if (declName != "") {
          os << " (in " << declName << ")";
        }
        os << ". ";

        os << "The assign property '" << *it << "' of the ";
        if (className != "") {
          os << "instance of " << className;
        } else {
          os << "object";
        }
        os << " stored in '" << ivarName << "' appears to occasionally point to self. ";

        os << "For memory safety, you need to clear this property explicitly before losing reference to this object, typically by adding a line: '" << ivarName << "." << *it << " = nil;'. ";

        os << "In case of a false warning, consider adding an assert instead: 'FBAssert(" << ivarName << "." << *it << " != self);' or, if applicable: 'FBAssert(!" << ivarName << ");'.";

        emitBugReport(os.str());
      }
    }
  }
Beispiel #13
0
 int MMKVImpl::SRem(DBID db, const Data& key, const DataArray& members)
 {
     if (m_readonly)
     {
         return ERR_PERMISSION_DENIED;
     }
     int err = 0;
     RWLockGuard<MemorySegmentManager, WRITE_LOCK> keylock_guard(m_segment);
     EnsureWritableValueSpace();
     StringSet* set = GetObject<StringSet>(db, key, V_TYPE_SET, false, err)();
     if (IS_NOT_EXISTS(err))
     {
         return 0;
     }
     if (NULL == set || 0 != err)
     {
         return err;
     }
     int removed = 0;
     for (size_t i = 0; i < members.size(); i++)
     {
         StringSet::iterator found = set->find(Object(members[i], true));
         if (found != set->end())
         {
             Object cc = *found;
             set->erase(found);
             DestroyObjectContent(cc);
             removed++;
         }
     }
     if (set->empty())
     {
         GenericDel(GetMMKVTable(db, false),db, Object(key, false));
     }
     return removed;
 }
Beispiel #14
0
void authorize(const AuthParams &challenge, AuthParams &authorization,
               const URI &uri, const std::string &method, const std::string &username,
               const std::string &password)
{
    std::string realm, qop, nonce, opaque, algorithm;
    StringMap::const_iterator it;
    if ( (it = challenge.parameters.find("realm")) != challenge.parameters.end()) realm = it->second;
    if ( (it = challenge.parameters.find("qop")) != challenge.parameters.end()) qop = it->second;
    if ( (it = challenge.parameters.find("nonce")) != challenge.parameters.end()) nonce = it->second;
    if ( (it = challenge.parameters.find("opaque")) != challenge.parameters.end()) opaque = it->second;
    if ( (it = challenge.parameters.find("algorithm")) != challenge.parameters.end()) algorithm = it->second;

    if (algorithm.empty())
        algorithm = "MD5";
    StringSet qopValues;
    bool authQop = false;
    // If the server specified a quality of protection (qop), make sure it allows "auth"
    if (!qop.empty()) {
        ListParser parser(qopValues);
        parser.run(qop);
        if (parser.error() || !parser.complete())
            MORDOR_THROW_EXCEPTION(BadMessageHeaderException());
        if (qopValues.find("auth") == qopValues.end())
            MORDOR_THROW_EXCEPTION(InvalidQopException(qop));
        authQop = true;
    }

    // come up with a suitable client nonce
    std::ostringstream os;
    os << std::hex << TimerManager::now();
    std::string cnonce = os.str();
    std::string nc = "00000001";

    // compute A1
    std::string A1;
    if (algorithm == "MD5")
        A1 = username + ':' + realm + ':' + password;
    else if (algorithm == "MD5-sess")
        A1 = md5( username + ':' + realm + ':' + password ) + ':' + nonce + ':' + cnonce;
    else
        MORDOR_THROW_EXCEPTION(InvalidAlgorithmException(algorithm));

    // compute A2 - our qop is always auth or unspecified
    os.str("");
    os << method << ':' << uri;
    std::string A2 = os.str();

    authorization.scheme = "Digest";
    authorization.base64.clear();
    authorization.parameters["username"] = username;
    authorization.parameters["realm"] = realm;
    authorization.parameters["nonce"] = nonce;
    authorization.parameters["uri"] = uri.toString();
    authorization.parameters["algorithm"] = algorithm;

    std::string response;
    if (authQop) {
        qop = "auth";
        response = md5( md5(A1) + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + md5(A2) );
        authorization.parameters["qop"] = qop;
        authorization.parameters["nc"] = nc;
        authorization.parameters["cnonce"] = cnonce;
    } else {
        response = md5( md5(A1) + ':' + nonce + ':' + md5(A2) );

    }
    authorization.parameters["response"] = response;
    if (!opaque.empty())
        authorization.parameters["opaque"] = opaque;
}
void SBSourcesBuildPhase::writeVCProjectFiles(VCProject& proj) const
{
  // We don't support source compilation when building bundles
  TargetProductType productType = m_parentTarget.getProductType();
  if (productType == TargetBundle)
  {
    if (!m_phase->getBuildFileList().empty()) {
      SBLog::warning() << "Ignoring all source files in \"" << m_parentTarget.getName() << "\" bundle target." << std::endl;
    }
    return;
  }

  SBBuildPhase::writeVSFileDescriptions(proj, "Text");

  String xcProjectDir = m_parentTarget.getProject().getProjectDir();
  String vsProjectDir = sb_dirname(proj.getPath());
  StringSet prefixHeaders;
  for (auto bs : m_parentTarget.getBuildSettings()) {
    VCProjectConfiguration* config = proj.addConfiguration(bs.first);

    // Prefix header (recalculate relative path)
    String prefixHeader = bs.second->getValue("GCC_PREFIX_HEADER");
    if (!prefixHeader.empty()) {
      String absHeaderPath = m_parentTarget.makeAbsolutePath(prefixHeader);
      String relHeaderPath = m_parentTarget.makeRelativePath(prefixHeader, vsProjectDir);;
      relHeaderPath = winPath(relHeaderPath);
      config->setItemDefinition("ClangCompile", "PrefixHeader", relHeaderPath);

      // Add plist file to project (only once)
      if (prefixHeaders.find(absHeaderPath) == prefixHeaders.end()) {
        addRelativeFilePathToVS("ClInclude", absHeaderPath, "", proj, *bs.second);
        prefixHeaders.insert(absHeaderPath);
      }
    }

    // Preprocessor definitions
    StringVec preprocessorTokens;
    bs.second->getValue("GCC_PREPROCESSOR_DEFINITIONS", preprocessorTokens);
    String preprocessorDefs = joinStrings(preprocessorTokens, ";");
    if (!preprocessorDefs.empty()) {
      config->setItemDefinition("ClangCompile", "PreprocessorDefinitions", preprocessorDefs);
    }

    // Optimization level
    String optimizationLevel = bs.second->getValue("GCC_OPTIMIZATION_LEVEL");
    if (!optimizationLevel.empty()) {
      String vsOptimizationLevel;
      if (optimizationLevel == "s") {
        vsOptimizationLevel = "MinSpace";
      } else if (optimizationLevel == "0") {
        vsOptimizationLevel = "Disabled";
      } else {
        vsOptimizationLevel = "MaxSpeed";
      }
      config->setItemDefinition("ClangCompile", "OptimizationLevel", vsOptimizationLevel);
    }

    // ARC
    String enableARC = bs.second->getValue("CLANG_ENABLE_OBJC_ARC");
    if (enableARC == "YES") {
      config->setItemDefinition("ClangCompile", "ObjectiveCARC", "true");
    }

    // Modules
    String enableModules = bs.second->getValue("CLANG_ENABLE_MODULES");
    if (enableModules == "YES") {
        config->setItemDefinition("ClangCompile", "ObjectiveCModules", "true");
    }

    // Header search paths (make them relative)
    StringVec includePaths;
    bs.second->getValue("HEADER_SEARCH_PATHS", includePaths);
    for (auto &cur : includePaths) {
      cur = m_parentTarget.makeRelativePath(cur, vsProjectDir);
      cur = winPath(cur);
    }
    includePaths.insert(includePaths.begin(), "$(SolutionPublicHeadersDir)");
    config->setItemDefinition("ClangCompile", "IncludePaths", joinStrings(includePaths, ";"));

    // User header search paths (make them relative)
    StringVec userIncludePaths;
    bs.second->getValue("USER_HEADER_SEARCH_PATHS", userIncludePaths);
    for (auto &cur : userIncludePaths) {
      cur = m_parentTarget.makeRelativePath(cur, vsProjectDir);
      cur = winPath(cur);
    }
    if (!userIncludePaths.empty()) {
      config->setItemDefinition("ClangCompile", "UserIncludePaths", joinStrings(userIncludePaths, ";"));
    }

    // Exclude search path subdirectories
    StringVec excludeSubDirectories;
    bs.second->getValue("EXCLUDED_RECURSIVE_SEARCH_PATH_SUBDIRECTORIES", excludeSubDirectories);
    if (!excludeSubDirectories.empty()) {
        config->setItemDefinition("ClangCompile", "ExcludedSearchPathSubdirectories", joinStrings(excludeSubDirectories, ";"));
    }

    // Header map
    if (bs.second->getValue("USE_HEADERMAP") == "YES") {
      if (bs.second->getValue("ALWAYS_SEARCH_USER_PATHS") == "YES") {
        config->setItemDefinition("ClangCompile", "HeaderMap", "Combined");
      } else if (bs.second->getValue("HEADERMAP_INCLUDES_PROJECT_HEADERS") == "YES") {
        config->setItemDefinition("ClangCompile", "HeaderMap", "Project");
      }
    }

    // Other C flags
    String otherCFlags = bs.second->getValue("OTHER_CFLAGS");
    processClangFlags(otherCFlags, xcProjectDir, vsProjectDir);
    if (!otherCFlags.empty()) {
      config->setItemDefinition("ClangCompile", "OtherCFlags", otherCFlags);
    }

    // Other C++ flags
    String otherCPlusPlusFlags = bs.second->getValue("OTHER_CPLUSPLUSFLAGS");
    processClangFlags(otherCPlusPlusFlags, xcProjectDir, vsProjectDir);
    if (!otherCPlusPlusFlags.empty()) {
      config->setItemDefinition("ClangCompile", "OtherCPlusPlusFlags", otherCPlusPlusFlags);
    }

    // CRT
    String configNameUpper = strToUpper(bs.first);
    if (configNameUpper.find("DEBUG") != String::npos) {
      config->setItemDefinition("ClangCompile", "RuntimeLibrary", "MultiThreadedDebugDLL");
    }
  }
}
Beispiel #16
0
/**
 * Scan a file for includes, defines and the lot.
 * @param filename the name of the file to scan.
 * @param ext the extension of the filename.
 * @param header whether the file is a header or not.
 * @param verbose whether to give verbose debugging information.
 */
void ScanFile(const char *filename, const char *ext, bool header, bool verbose)
{
	static StringSet defines;
	static std::stack<Ignore> ignore;
	/* Copy in the default defines (parameters of depend) */
	if (!header) {
		for (StringSet::iterator it = _defines.begin(); it != _defines.end(); it++) {
			defines.insert(strdup(*it));
		}
	}

	File file(filename);
	Lexer lexer(&file);

	/* Start the lexing! */
	lexer.Lex();

	while (lexer.GetToken() != TOKEN_END) {
		switch (lexer.GetToken()) {
			/* We reached the end of the file... yay, we're done! */
			case TOKEN_END: break;

			/* The line started with a # (minus whitespace) */
			case TOKEN_SHARP:
				lexer.Lex();
				switch (lexer.GetToken()) {
					case TOKEN_INCLUDE:
						if (verbose) fprintf(stderr, "%s #include ", filename);
						lexer.Lex();
						switch (lexer.GetToken()) {
							case TOKEN_LOCAL:
							case TOKEN_GLOBAL: {
								if (verbose) fprintf(stderr, "%s", lexer.GetString());
								if (!ignore.empty() && ignore.top() != NOT_IGNORE) {
									if (verbose) fprintf(stderr, " (ignored)");
									break;
								}
								const char *h = GeneratePath(file.GetDirname(), lexer.GetString(), lexer.GetToken() == TOKEN_LOCAL);
								if (h != NULL) {
									StringMap::iterator it = _headers.find(h);
									if (it == _headers.end()) {
										it = (_headers.insert(StringMapItem(strdup(h), new StringSet()))).first;
										if (verbose) fprintf(stderr, "\n");
										ScanFile(h, ext, true, verbose);
									}
									StringMap::iterator curfile;
									if (header) {
										curfile = _headers.find(filename);
									} else {
										/* Replace the extension with the provided extension of '.o'. */
										char path[PATH_MAX];
										strcpy(path, filename);
										*(strrchr(path, '.')) = '\0';
										strcat(path, ext != NULL ? ext : ".o");
										curfile = _files.find(path);
										if (curfile == _files.end()) {
											curfile = (_files.insert(StringMapItem(strdup(path), new StringSet()))).first;
										}
									}
									if (it != _headers.end()) {
										for (StringSet::iterator header = it->second->begin(); header != it->second->end(); header++) {
											if (curfile->second->find(*header) == curfile->second->end()) curfile->second->insert(strdup(*header));
										}
									}
									if (curfile->second->find(h) == curfile->second->end()) curfile->second->insert(strdup(h));
									free(h);
								}
							}
							/* FALL THROUGH */
							default: break;
						}
						break;

					case TOKEN_DEFINE:
						if (verbose) fprintf(stderr, "%s #define ", filename);
						lexer.Lex();
						if (lexer.GetToken() == TOKEN_IDENTIFIER) {
							if (verbose) fprintf(stderr, "%s", lexer.GetString());
							if (!ignore.empty() && ignore.top() != NOT_IGNORE) {
								if (verbose) fprintf(stderr, " (ignored)");
								break;
							}
							if (defines.find(lexer.GetString()) == defines.end()) defines.insert(strdup(lexer.GetString()));
							lexer.Lex();
						}
						break;

					case TOKEN_UNDEF:
						if (verbose) fprintf(stderr, "%s #undef ", filename);
						lexer.Lex();
						if (lexer.GetToken() == TOKEN_IDENTIFIER) {
							if (verbose) fprintf(stderr, "%s", lexer.GetString());
							if (!ignore.empty() && ignore.top() != NOT_IGNORE) {
								if (verbose) fprintf(stderr, " (ignored)");
								break;
							}
							StringSet::iterator it = defines.find(lexer.GetString());
							if (it != defines.end()) {
								free(*it);
								defines.erase(it);
							}
							lexer.Lex();
						}
						break;

					case TOKEN_ENDIF:
						if (verbose) fprintf(stderr, "%s #endif", filename);
						lexer.Lex();
						if (!ignore.empty()) ignore.pop();
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;

					case TOKEN_ELSE: {
						if (verbose) fprintf(stderr, "%s #else", filename);
						lexer.Lex();
						Ignore last = ignore.empty() ? NOT_IGNORE : ignore.top();
						if (!ignore.empty()) ignore.pop();
						if (ignore.empty() || ignore.top() == NOT_IGNORE) {
							ignore.push(last == IGNORE_UNTIL_ELSE ? NOT_IGNORE : IGNORE_UNTIL_ENDIF);
						} else {
							ignore.push(IGNORE_UNTIL_ENDIF);
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;
					}

					case TOKEN_ELIF: {
						if (verbose) fprintf(stderr, "%s #elif ", filename);
						lexer.Lex();
						Ignore last = ignore.empty() ? NOT_IGNORE : ignore.top();
						if (!ignore.empty()) ignore.pop();
						if (ignore.empty() || ignore.top() == NOT_IGNORE) {
							bool value = ExpressionOr(&lexer, &defines, verbose);
							ignore.push(last == IGNORE_UNTIL_ELSE ? (value ? NOT_IGNORE : IGNORE_UNTIL_ELSE) : IGNORE_UNTIL_ENDIF);
						} else {
							ignore.push(IGNORE_UNTIL_ENDIF);
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;
					}

					case TOKEN_IF: {
						if (verbose) fprintf(stderr, "%s #if ", filename);
						lexer.Lex();
						if (ignore.empty() || ignore.top() == NOT_IGNORE) {
							bool value = ExpressionOr(&lexer, &defines, verbose);
							ignore.push(value ? NOT_IGNORE : IGNORE_UNTIL_ELSE);
						} else {
							ignore.push(IGNORE_UNTIL_ENDIF);
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;
					}

					case TOKEN_IFDEF:
						if (verbose) fprintf(stderr, "%s #ifdef ", filename);
						lexer.Lex();
						if (lexer.GetToken() == TOKEN_IDENTIFIER) {
							bool value = defines.find(lexer.GetString()) != defines.end();
							if (verbose) fprintf(stderr, "%s[%d]", lexer.GetString(), value);
							if (ignore.empty() || ignore.top() == NOT_IGNORE) {
								ignore.push(value ? NOT_IGNORE : IGNORE_UNTIL_ELSE);
							} else {
								ignore.push(IGNORE_UNTIL_ENDIF);
							}
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;

					case TOKEN_IFNDEF:
						if (verbose) fprintf(stderr, "%s #ifndef ", filename);
						lexer.Lex();
						if (lexer.GetToken() == TOKEN_IDENTIFIER) {
							bool value = defines.find(lexer.GetString()) != defines.end();
							if (verbose) fprintf(stderr, "%s[%d]", lexer.GetString(), value);
							if (ignore.empty() || ignore.top() == NOT_IGNORE) {
								ignore.push(!value ? NOT_IGNORE : IGNORE_UNTIL_ELSE);
							} else {
								ignore.push(IGNORE_UNTIL_ENDIF);
							}
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;

					default:
						if (verbose) fprintf(stderr, "%s #<unknown>", filename);
						lexer.Lex();
						break;
				}
				if (verbose) fprintf(stderr, "\n");
				/* FALL THROUGH */
			default:
				/* Ignore the rest of the garbage on this line */
				while (lexer.GetToken() != TOKEN_EOL && lexer.GetToken() != TOKEN_END) lexer.Lex();
				lexer.Lex();
				break;
		}
	}

	if (!header) {
		for (StringSet::iterator it = defines.begin(); it != defines.end(); it++) {
			free(*it);
		}
		defines.clear();
		while (!ignore.empty()) ignore.pop();
	}
}
Beispiel #17
0
std::string UdmComparator::ObjectName::operator()( Udm::Object udmObject ) {

	static StringSet reportedClassNameSet;

	Uml::Class umlClass = udmObject.type();
	Uml::Attribute umlNameAttribute;

	UmlClassNameAttributeMap::iterator cnmItr = _umlClassNameAttributeMap.find( umlClass );
	if ( cnmItr != _umlClassNameAttributeMap.end() ) {

		umlNameAttribute = cnmItr->second;

	} else {

		NameUmlAttributeMap nameUmlAttributeMap = getNameUmlAttributeMap( umlClass );
			
		NameUmlAttributeMap::iterator numItr = nameUmlAttributeMap.find( "name" );
		if ( numItr != nameUmlAttributeMap.end() ) {

			umlNameAttribute = numItr->second;

		} else {

			numItr = nameUmlAttributeMap.find( "Name" );
			if ( numItr != nameUmlAttributeMap.end() ) {

				umlNameAttribute = numItr->second;

			} else if (  static_cast< std::string >( umlClass.stereotype() ) != "Connection"  ) {

				std::string className = umlClass.name();
				if ( reportedClassNameSet.find( className ) == reportedClassNameSet.end() ) {
					std::cerr << "WARNING: Class \"" << className << "\" has no \"[Nn]ame\" attribute." << std::endl << std::endl;
					reportedClassNameSet.insert( className );
				}
				return "";

			}

		}

		_umlClassNameAttributeMap.insert(  std::make_pair( umlClass, umlNameAttribute )  );

	}

	std::string udmObjectName = "";
	if ( umlNameAttribute != Udm::null ) {
		udmObjectName = udmObject.getStringAttr( umlNameAttribute );
		if (  umlClass.stereotype() == "Connection" && udmObjectName == static_cast< std::string >( umlClass.name() )  ) {
			udmObjectName = "";
		}
	}

	if ( udmObjectName == "" && umlClass.stereotype() == "Connection" ) {

		UmlAssociationRoleSet umlAssociationRoleSet = getAllUmlAssociationRoles( umlClass );

		for( UmlAssociationRoleSet::iterator arsItr = umlAssociationRoleSet.begin() ; arsItr != umlAssociationRoleSet.end() ; ++arsItr ) {
			
			UdmObjectSet udmObjectSet = udmObject.getAssociation( *arsItr, Udm::TARGETFROMCLASS );
			for( UdmObjectSet::iterator uosItr = udmObjectSet.begin() ; uosItr != udmObjectSet.end() ; ++uosItr ) {

				if ( !udmObjectName.empty() ) udmObjectName += ":";
				udmObjectName += (*this)(*uosItr);

			}

		}

		if ( umlNameAttribute != Udm::null ) {
			udmObject.setStringAttr( umlNameAttribute, udmObjectName );
		}

	}

	Udm::Object udmObjectParent = udmObject.GetParent();

	if ( udmObjectParent != Udm::null ) {
		const auto& it = ObjectNameCache.find(udmObjectParent);
		if (it != ObjectNameCache.end())
		{
			udmObjectName = it->second + "/" + udmObjectName;
		}
		else
		{
			udmObjectName = operator()( udmObjectParent ) + "/" + udmObjectName;
		}
	}

	return udmObjectName;
}
Beispiel #18
0
// _LoadAddOns
status_t
DiskSystemAddOnManager::_LoadAddOns(StringSet& alreadyLoaded,
                                    directory_which addOnDir)
{
    // get the add-on directory path
    BPath path;
    status_t error = find_directory(addOnDir, &path, false);
    if (error != B_OK)
        return error;

    TRACE("DiskSystemAddOnManager::_LoadAddOns(): %s\n", path.Path());

    error = path.Append("disk_systems");
    if (error != B_OK)
        return error;

    if (!BEntry(path.Path()).Exists())
        return B_OK;

    // open the directory and iterate through its entries
    BDirectory directory;
    error = directory.SetTo(path.Path());
    if (error != B_OK)
        return error;

    entry_ref ref;
    while (directory.GetNextRef(&ref) == B_OK) {
        // skip, if already loaded
        if (alreadyLoaded.find(ref.name) != alreadyLoaded.end()) {
            TRACE("  skipping \"%s\" -- already loaded\n", ref.name);
            continue;
        }

        // get the entry path
        BPath entryPath;
        error = entryPath.SetTo(&ref);
        if (error != B_OK) {
            if (error == B_NO_MEMORY)
                return error;
            TRACE("  skipping \"%s\" -- failed to get path\n", ref.name);
            continue;
        }

        // load the add-on
        image_id image = load_add_on(entryPath.Path());
        if (image < 0) {
            TRACE("  skipping \"%s\" -- failed to load add-on\n", ref.name);
            continue;
        }

        AddOnImage* addOnImage = new(nothrow) AddOnImage(image);
        if (!addOnImage) {
            unload_add_on(image);
            return B_NO_MEMORY;
        }
        ObjectDeleter<AddOnImage> addOnImageDeleter(addOnImage);

        // get the add-on objects
        status_t (*getAddOns)(BList*);
        error = get_image_symbol(image, "get_disk_system_add_ons",
                                 B_SYMBOL_TYPE_TEXT, (void**)&getAddOns);
        if (error != B_OK) {
            TRACE("  skipping \"%s\" -- function symbol not found\n", ref.name);
            continue;
        }

        BList addOns;
        error = getAddOns(&addOns);
        if (error != B_OK || addOns.IsEmpty()) {
            TRACE("  skipping \"%s\" -- getting add-ons failed\n", ref.name);
            continue;
        }

        // create and add AddOn objects
        int32 count = addOns.CountItems();
        for (int32 i = 0; i < count; i++) {
            BDiskSystemAddOn* diskSystemAddOn
                = (BDiskSystemAddOn*)addOns.ItemAt(i);
            AddOn* addOn = new(nothrow) AddOn(addOnImage, diskSystemAddOn);
            if (!addOn)
                return B_NO_MEMORY;

            if (fAddOns.AddItem(addOn)) {
                addOnImage->refCount++;
                addOnImageDeleter.Detach();
            } else {
                delete addOn;
                return B_NO_MEMORY;
            }
        }

        TRACE("  got %ld BDiskSystemAddOn(s) from add-on \"%s\"\n", count,
              ref.name);

        // add the add-on name to the set of already loaded add-ons
        try {
            alreadyLoaded.insert(ref.name);
        } catch (std::bad_alloc& exception) {
            return B_NO_MEMORY;
        }
    }

    return B_OK;
}
	void ATIExecutableKernel::initializeSharedMemory()
	{
		report("Allocating shared memory");

		typedef std::unordered_map<std::string, size_t> AllocationMap;
		typedef std::unordered_set<std::string> StringSet;
		typedef std::deque<ir::PTXOperand*> OperandVector;
		typedef std::unordered_map<std::string,
				ir::Module::GlobalMap::const_iterator> GlobalMap;

		AllocationMap map;
		GlobalMap sharedGlobals;
		StringSet external;
		OperandVector externalOperands;

		unsigned int externalAlignment = 1;
		size_t sharedSize = 0;

		assert(module != 0);

		// global shared variables
		ir::Module::GlobalMap globals = module->globals();
		ir::Module::GlobalMap::const_iterator global;
		for (global = globals.begin() ; global != globals.end() ; global++)
		{
			ir::PTXStatement statement = global->second.statement;
			if (statement.directive == ir::PTXStatement::Shared)
			{
				if (statement.attribute == ir::PTXStatement::Extern)
				{
					report("Found global external shared variable \""
							<< statement.name << "\"");

					assertM(external.count(statement.name) == 0,
							"External global \"" << statement.name
							<< "\" declared more than once.");

					external.insert(statement.name);
					externalAlignment = std::max(externalAlignment,
							(unsigned int)statement.alignment);
					externalAlignment = std::max(externalAlignment,
							ir::PTXOperand::bytes(statement.type));
				} else {
					report("Found global shared variable \"" 
							<< statement.name << "\"");
					sharedGlobals.insert(
							std::make_pair(statement.name, global));
				}
			}
		}

		// local shared variables	
		LocalMap::const_iterator local;
		for (local = locals.begin() ; local != locals.end() ; local++)
		{
			if (local->second.space == ir::PTXInstruction::Shared)
			{
				if (local->second.attribute == ir::PTXStatement::Extern)
				{
					report("Found local external shared variable \"" 
							<< local->second.name << "\"");

					assertM(external.count(local->second.name) == 0,
							"External local \"" << local->second.name
							<< "\" declared more than once.");

					external.insert(local->second.name);
					externalAlignment = std::max(externalAlignment,
							(unsigned int)local->second.alignment);
					externalAlignment = std::max(externalAlignment,
							ir::PTXOperand::bytes(local->second.type));
				} else
				{
					report("Allocating local shared variable \""
							<< local->second.name << "\" of size "
							<< local->second.getSize());

					_pad(sharedSize, local->second.alignment);
					map.insert(std::make_pair(local->second.name, sharedSize));
					sharedSize += local->second.getSize();
				}
			}
		}

		ir::ControlFlowGraph::iterator block;
		for (block = cfg()->begin() ; block != cfg()->end() ; block++)
		{
			ir::ControlFlowGraph::InstructionList insts = block->instructions;
			ir::ControlFlowGraph::InstructionList::iterator inst;
			for (inst = insts.begin() ; inst != insts.end() ; inst++)
			{
				ir::PTXInstruction& ptx = 
					static_cast<ir::PTXInstruction&>(**inst);

				if (ptx.opcode == ir::PTXInstruction::Mov ||
						ptx.opcode == ir::PTXInstruction::Ld ||
						ptx.opcode == ir::PTXInstruction::St)
				{
					ir::PTXOperand* operands[] = {&ptx.d, &ptx.a, &ptx.b, 
						&ptx.c};

					for (unsigned int i = 0 ; i != 4 ; i++)
					{
						ir::PTXOperand* operand = operands[i];

						if (operand->addressMode == ir::PTXOperand::Address)
						{
							StringSet::iterator si = 
								external.find(operand->identifier);
							if (si != external.end())
							{
								report("For instruction \""
										<< ptx.toString()
										<< "\", mapping shared label \"" << *si
										<< "\" to external shared memory.");
								externalOperands.push_back(operand);
								continue;
							}

							GlobalMap::iterator gi = 
								sharedGlobals.find(operand->identifier);
							if (gi != sharedGlobals.end())
							{
								ir::Module::GlobalMap::const_iterator it = 
									gi->second;
								sharedGlobals.erase(gi);

								report("Allocating global shared variable \""
										<< it->second.statement.name << "\"");

								map.insert(std::make_pair(
											it->second.statement.name, 
											sharedSize));
								sharedSize += it->second.statement.bytes();
							}

							AllocationMap::iterator mapping = 
								map.find(operand->identifier);
							if (mapping != map.end())
							{
								report("For instruction " << ptx.toString()
										<< ", mapping shared label "
										<< mapping->first << " to " << 
										mapping->second);

								operand->addressMode = 
									ir::PTXOperand::Immediate;
								operand->imm_uint = mapping->second;
							}
						}
					}
				}
			}
		}

		_pad(sharedSize, externalAlignment);

		report("Mapping external shared variables.");
		OperandVector::iterator operand;
		for (operand = externalOperands.begin() ; 
				operand != externalOperands.end() ; operand++)
		{
			report("Mapping external shared label \""
					<< (*operand)->identifier << "\" to " << sharedSize);
			(*operand)->addressMode = ir::PTXOperand::Immediate;
			(*operand)->imm_uint = sharedSize;
		}

		// allocate shared memory object
		_sharedMemorySize = sharedSize;

		report("Total shared memory size is " << _sharedMemorySize);
	}
Beispiel #20
0
Error DiffStyle::diffStringTable() {
  DiffPrinter D(2, "String Table", 30, 20, opts::diff::PrintResultColumn,
                opts::diff::PrintValueColumns, outs());
  D.printExplicit("File", DiffResult::UNSPECIFIED,
                  truncateStringFront(File1.getFilePath(), 18),
                  truncateStringFront(File2.getFilePath(), 18));

  auto ExpectedST1 = File1.getStringTable();
  auto ExpectedST2 = File2.getStringTable();
  bool Has1 = !!ExpectedST1;
  bool Has2 = !!ExpectedST2;
  std::string Count1 = Has1 ? llvm::utostr(ExpectedST1->getNameCount())
                            : "(string table not present)";
  std::string Count2 = Has2 ? llvm::utostr(ExpectedST2->getNameCount())
                            : "(string table not present)";
  D.print("Number of Strings", Count1, Count2);

  if (!Has1 || !Has2) {
    consumeError(ExpectedST1.takeError());
    consumeError(ExpectedST2.takeError());
    return Error::success();
  }

  auto &ST1 = *ExpectedST1;
  auto &ST2 = *ExpectedST2;

  D.print("Hash Version", ST1.getHashVersion(), ST2.getHashVersion());
  D.print("Byte Size", ST1.getByteSize(), ST2.getByteSize());
  D.print("Signature", ST1.getSignature(), ST2.getSignature());

  // Both have a valid string table, dive in and compare individual strings.

  auto IdList1 = ST1.name_ids();
  auto IdList2 = ST2.name_ids();
  StringSet<> LS;
  StringSet<> RS;
  uint32_t Empty1 = 0;
  uint32_t Empty2 = 0;
  for (auto ID : IdList1) {
    auto S = ST1.getStringForID(ID);
    if (!S)
      return S.takeError();
    if (S->empty())
      ++Empty1;
    else
      LS.insert(*S);
  }
  for (auto ID : IdList2) {
    auto S = ST2.getStringForID(ID);
    if (!S)
      return S.takeError();
    if (S->empty())
      ++Empty2;
    else
      RS.insert(*S);
  }
  D.print("Empty Strings", Empty1, Empty2);

  for (const auto &S : LS) {
    auto R = RS.find(S.getKey());
    std::string Truncated = truncateStringMiddle(S.getKey(), 28);
    uint32_t I = cantFail(ST1.getIDForString(S.getKey()));
    if (R == RS.end()) {
      D.printExplicit(Truncated, DiffResult::DIFFERENT, I, "(not present)");
      continue;
    }

    uint32_t J = cantFail(ST2.getIDForString(R->getKey()));
    D.print<EquivalentDiffProvider>(Truncated, I, J);
    RS.erase(R);
  }

  for (const auto &S : RS) {
    auto L = LS.find(S.getKey());
    std::string Truncated = truncateStringMiddle(S.getKey(), 28);
    uint32_t J = cantFail(ST2.getIDForString(S.getKey()));
    if (L == LS.end()) {
      D.printExplicit(Truncated, DiffResult::DIFFERENT, "(not present)", J);
      continue;
    }

    uint32_t I = cantFail(ST1.getIDForString(L->getKey()));
    D.print<EquivalentDiffProvider>(Truncated, I, J);
  }
  return Error::success();
}
Beispiel #21
0
//-----------------------------------------------------------------------
void Compositor::createGlobalTextures()
{
    static size_t dummyCounter = 0;
    if (mSupportedTechniques.empty())
        return;

    //To make sure that we are consistent, it is demanded that all composition
    //techniques define the same set of global textures.

    typedef std::set<String> StringSet;
    StringSet globalTextureNames;

    //Initialize global textures from first supported technique
    CompositionTechnique* firstTechnique = mSupportedTechniques[0];

    CompositionTechnique::TextureDefinitionIterator texDefIt =
        firstTechnique->getTextureDefinitionIterator();
    while (texDefIt.hasMoreElements())
    {
        CompositionTechnique::TextureDefinition* def = texDefIt.getNext();
        if (def->scope == CompositionTechnique::TS_GLOBAL)
        {
            //Check that this is a legit global texture
            if (!def->refCompName.empty())
            {
                OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                            "Global compositor texture definition can not be a reference",
                            "Compositor::createGlobalTextures");
            }
            if (def->width == 0 || def->height == 0)
            {
                OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                            "Global compositor texture definition must have absolute size",
                            "Compositor::createGlobalTextures");
            }
            if (def->pooled)
            {
                LogManager::getSingleton().logMessage(
                    "Pooling global compositor textures has no effect");
            }
            globalTextureNames.insert(def->name);

            //TODO GSOC : Heavy copy-pasting from CompositorInstance. How to we solve it?

            /// Make the tetxure
            RenderTarget* rendTarget;
            if (def->formatList.size() > 1)
            {
                String MRTbaseName = "c" + StringConverter::toString(dummyCounter++) +
                                     "/" + mName + "/" + def->name;
                MultiRenderTarget* mrt =
                    Root::getSingleton().getRenderSystem()->createMultiRenderTarget(MRTbaseName);
                mGlobalMRTs[def->name] = mrt;

                // create and bind individual surfaces
                size_t atch = 0;
                for (PixelFormatList::iterator p = def->formatList.begin();
                        p != def->formatList.end(); ++p, ++atch)
                {

                    String texname = MRTbaseName + "/" + StringConverter::toString(atch);
                    TexturePtr tex;

                    tex = TextureManager::getSingleton().createManual(
                              texname,
                              ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
                              (uint)def->width, (uint)def->height, 0, *p, TU_RENDERTARGET, 0,
                              def->hwGammaWrite && !PixelUtil::isFloatingPoint(*p), def->fsaa);

                    RenderTexture* rt = tex->getBuffer()->getRenderTarget();
                    rt->setAutoUpdated(false);
                    mrt->bindSurface(atch, rt);

                    // Also add to local textures so we can look up
                    String mrtLocalName = getMRTTexLocalName(def->name, atch);
                    mGlobalTextures[mrtLocalName] = tex;

                }

                rendTarget = mrt;
            }
            else
            {
                String texName =  "c" + StringConverter::toString(dummyCounter++) +
                                  "/" + mName + "/" + def->name;

                // space in the name mixup the cegui in the compositor demo
                // this is an auto generated name - so no spaces can't hart us.
                std::replace( texName.begin(), texName.end(), ' ', '_' );

                TexturePtr tex;
                tex = TextureManager::getSingleton().createManual(
                          texName,
                          ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
                          (uint)def->width, (uint)def->height, 0, def->formatList[0], TU_RENDERTARGET, 0,
                          def->hwGammaWrite && !PixelUtil::isFloatingPoint(def->formatList[0]), def->fsaa);


                rendTarget = tex->getBuffer()->getRenderTarget();
                mGlobalTextures[def->name] = tex;
            }

            //Set DepthBuffer pool for sharing
            rendTarget->setDepthBufferPool( def->depthBufferId );
        }
    }

    //Validate that all other supported techniques expose the same set of global textures.
    for (size_t i=1; i<mSupportedTechniques.size(); i++)
    {
        CompositionTechnique* technique = mSupportedTechniques[i];
        bool isConsistent = true;
        size_t numGlobals = 0;
        texDefIt = technique->getTextureDefinitionIterator();
        while (texDefIt.hasMoreElements())
        {
            CompositionTechnique::TextureDefinition* texDef = texDefIt.getNext();
            if (texDef->scope == CompositionTechnique::TS_GLOBAL)
            {
                if (globalTextureNames.find(texDef->name) == globalTextureNames.end())
                {
                    isConsistent = false;
                    break;
                }
                numGlobals++;
            }
        }
        if (numGlobals != globalTextureNames.size())
            isConsistent = false;

        if (!isConsistent)
        {
            OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                        "Different composition techniques define different global textures",
                        "Compositor::createGlobalTextures");
        }

    }

}
TEST_F(IddFixture,IddFactory_Units) {
    std::vector<boost::regex> unsupported;
    unsupported.push_back(boost::regex("\\$"));
    unsupported.push_back(boost::regex("eV"));
    unsupported.push_back(boost::regex("hh:mm"));
    unsupported.push_back(boost::regex("percent"));
    unsupported.push_back(boost::regex("ppm"));

    IddObjectVector objects = IddFactory::instance().getObjects(IddFileType(IddFileType::WholeFactory));
    StringSet goodUnits;
    StringSet badUnits;
    for (const IddObject& object : objects) {
        IddFieldVector fields = object.nonextensibleFields();
        IddFieldVector temp = object.extensibleGroup();
        fields.insert(fields.end(),temp.begin(),temp.end());
        for (const IddField& field : fields) {
            OptionalString iddUnits = field.properties().units;
            OptionalUnit siUnit;
            if (iddUnits) {

                // check if already tested units
                if (goodUnits.find(*iddUnits) != goodUnits.end()) {
                    continue;
                }
                if (badUnits.find(*iddUnits) != badUnits.end()) {
                    continue;
                }

                // screen for unsupported units
                for (const boost::regex& re : unsupported) {
                    if (boost::regex_search(*iddUnits,re)) {
                        iddUnits = boost::none;
                        break;
                    }
                }
                if (!iddUnits) {
                    continue;
                }

                siUnit = field.getUnits(false);
                EXPECT_TRUE(siUnit || field.unitsBasedOnOtherField()) << object.name() << " field: " << field.name();
                if (siUnit) {
                    // could just return junk unit. if not junk, quantity will be convertible
                    // to UnitSystem::SI.
                    Quantity q(1.0,*siUnit);
                    OptionalQuantity testQ = convert(q,UnitSystem(UnitSystem::SI));
                    EXPECT_TRUE(testQ) << "Unable to convert unit '" << *iddUnits << "' to SI for field '"
                                       << field.name() << "' in IddObject '" << object.name() << "'.";
                    if (testQ) {
                        goodUnits.insert(*iddUnits);
                        EXPECT_TRUE(testQ->system() == UnitSystem::SI);
                    } else {
                        badUnits.insert(*iddUnits);
                        LOG(Debug,"Unable to convert unit '" << *iddUnits << "' to SI for field '"
                            << field.name() << "' in IddObject '" << object.name() << "'.");
                    }
                }
                else if (field.unitsBasedOnOtherField()) {
                    goodUnits.insert(*iddUnits);
                    continue;
                }
                else {
                    badUnits.insert(*iddUnits);
                    LOG(Debug,"Unable to instantiate unit '" << *iddUnits << "' for field '"
                        << field.name() << "' in IddObject '" << object.name() << "'.");
                    continue;
                }
                OptionalUnit ipUnit = field.getUnits(true);
                EXPECT_TRUE(ipUnit);
                if (ipUnit) {
                    // could just return junk unit. if not junk, quantity will be convertable
                    // to *siUnit or UnitSystem::SI.
                    Quantity q(1.0,*ipUnit);
                    OptionalQuantity testQ;
                    if (siUnit) {
                        testQ = convert(q,*siUnit);
                    }
                    else {
                        testQ = convert(q,UnitSystem(UnitSystem::SI));
                    }
                    EXPECT_TRUE(testQ);
                    if (testQ) {
                        goodUnits.insert(*iddUnits);
                    }
                    else {
                        badUnits.insert(ipUnit->standardString());
                        LOG(Debug,"Unable to convert unit " << *ipUnit << " to IDD/SI units " << *siUnit
                            << " for field '" << field.name() << "' in IddObject '" << object.name() << "'.");
                    }
                }
                else {
                    badUnits.insert(*iddUnits);
                    LOG(Debug,"Unable to instantiate ipUnit for field " << field.name() << " in IddObject "
                        << object.name() << ", which has units " << *siUnit << ".");
                }
            }
        }
    }
    LOG(Info,"IddUnitStrings not handled properly by the Factories and Converter:");
    for (const std::string& str : badUnits) {
        LOG(Info,"  " << str);
    }
    LOG(Info,"IddUnitStrings handled properly by the Factories and Converter:");
    for (const std::string& str : goodUnits) {
        LOG(Info,"  " << str);
    }
}
Beispiel #23
0
void DataLint::report()
{
    if (m_enabled)
    {
        // Error Assets

        DEBUG_REPORT_LOG_PRINT(true, ("Writing error files\n"));

        // Setup filenames for client versus server mode

        std::string dataLintErrorsAll((m_mode == M_client) ? "DataLint_Errors_All.txt" : "DataLintServer_Errors_All.txt");
        std::string dataLintErrorsAllFatal((m_mode == M_client) ? "DataLint_Errors_All_Fatal.txt" : "DataLintServer_Errors_All_Fatal.txt");
        std::string dataLintErrorsAllWarning((m_mode == M_client) ? "DataLint_Errors_All_Warning.txt" : "DataLintServer_Errors_All_Warning.txt");
        std::string dataLintErrorsAllObjectTemplate((m_mode == M_client) ? "DataLint_Errors_ObjectTemplate.txt" : "DataLintServer_Errors_ObjectTemplate.txt");

        // Server/client

        FILE *assetErrorFileAll                   = fopen(dataLintErrorsAll.c_str(), "wt");
        FILE *assetErrorFileAllFatal              = fopen(dataLintErrorsAllFatal.c_str(), "wt");
        FILE *assetErrorFileAllWarning            = fopen(dataLintErrorsAllWarning.c_str(), "wt");
        FILE *assetErrorFileObjectTemplate        = fopen(dataLintErrorsAllObjectTemplate.c_str(), "wt");

        // Client only

        FILE *assetErrorFileAppearance = NULL;
        FILE *assetErrorFileArrangementDescriptor = NULL;
        FILE *assetErrorFileLocalizedStringTable = NULL;
        FILE *assetErrorFilePortalProperty = NULL;
        FILE *assetErrorFileShaderTemplate = NULL;
        FILE *assetErrorFileSkyBox = NULL;
        FILE *assetErrorFileSlotDescriptor = NULL;
        FILE *assetErrorFileSoundTemplate = NULL;
        FILE *assetErrorFileTerrain = NULL;
        FILE *assetErrorFileTexture = NULL;
        FILE *assetErrorFileTextureRenderer = NULL;

        if (m_mode == M_client)
        {
            assetErrorFileAppearance            = fopen("DataLint_Errors_Appearance.txt", "wt");
            assetErrorFileArrangementDescriptor = fopen("DataLint_Errors_ArrangementDescriptor.txt", "wt");
            assetErrorFileLocalizedStringTable  = fopen("DataLint_Errors_LocalizedStringTable.txt", "wt");
            assetErrorFilePortalProperty        = fopen("DataLint_Errors_PortalProperty.txt", "wt");
            assetErrorFileShaderTemplate        = fopen("DataLint_Errors_ShaderTemplate.txt", "wt");
            assetErrorFileSkyBox                = fopen("DataLint_Errors_SkyBox.txt", "wt");
            assetErrorFileSlotDescriptor        = fopen("DataLint_Errors_SlotDescriptor.txt", "wt");
            assetErrorFileSoundTemplate         = fopen("DataLint_Errors_SoundTemplate.txt", "wt");
            assetErrorFileTerrain               = fopen("DataLint_Errors_Terrain.txt", "wt");
            assetErrorFileTexture               = fopen("DataLint_Errors_Texture.txt", "wt");
            assetErrorFileTextureRenderer       = fopen("DataLint_Errors_TextureRenderer.txt", "wt");
        }

        // Might want to think of a better way to keep track of the number of errors for each specific asset type.

        int totalErrorCountAll = 1;
        int totalErrorCountAllFatal = 1;
        int totalErrorCountAllWarning = 1;
        int totalErrorCountAppearance = 1;
        int totalErrorCountArrangementDescriptor = 1;
        int totalErrorCountLocalizedStringTable = 1;
        int totalErrorCountObjectTemplate = 1;
        int totalErrorCountPortalProperty = 1;
        int totalErrorCountShaderTemplate = 1;
        int totalErrorCountSkyBox = 1;
        int totalErrorCountSlotDescriptor = 1;
        int totalErrorCountSoundTemplate = 1;
        int totalErrorCountTerrain = 1;
        int totalErrorCountTexture = 1;
        int totalErrorCountTextureRenderer = 1;

        typedef std::set<std::string> StringSet;
        StringSet duplicateStringSet;

        if (assetErrorFileAll)
        {
            WarningList::iterator warningListIter = m_warningList->begin();

            for (; warningListIter != m_warningList->end(); ++warningListIter)
            {
                // Build a duplicate string

                std::string duplicateString(warningListIter->first);

                StringList::const_iterator stringStackIter = warningListIter->second.second.begin();

                for (; stringStackIter != warningListIter->second.second.end(); ++stringStackIter)
                {
                    duplicateString += *stringStackIter;
                }

                if (duplicateStringSet.find(duplicateString) == duplicateStringSet.end())
                {
                    // This is the first instance of this error, so log it

                    duplicateStringSet.insert(duplicateString);
                }
                else
                {
                    // We found a duplicate warning, so don't show it twice

                    continue;
                }

                // Write the error to the appropriate error file

                switch (warningListIter->second.first)
                {
                case AT_appearance:
                {
                    if (m_mode == M_client)
                    {
                        writeError(assetErrorFileAppearance, *warningListIter, totalErrorCountAppearance);
                    }
                }
                break;
                case AT_arrangementDescriptor:
                {
                    if (m_mode == M_client)
                    {
                        writeError(assetErrorFileArrangementDescriptor, *warningListIter, totalErrorCountArrangementDescriptor);
                    }
                }
                break;
                case AT_localizedStringTable:
                {
                    if (m_mode == M_client)
                    {
                        writeError(assetErrorFileLocalizedStringTable, *warningListIter, totalErrorCountLocalizedStringTable);
                    }
                }
                break;
                case AT_objectTemplate:
                {
                    writeError(assetErrorFileObjectTemplate, *warningListIter, totalErrorCountObjectTemplate);
                }
                break;
                case AT_portalProperty:
                {
                    if (m_mode == M_client)
                    {
                        writeError(assetErrorFilePortalProperty, *warningListIter, totalErrorCountPortalProperty);
                    }
                }
                break;
                case AT_shaderTemplate:
                {
                    if (m_mode == M_client)
                    {
                        writeError(assetErrorFileShaderTemplate, *warningListIter, totalErrorCountShaderTemplate);
                    }
                }
                break;
                case AT_skyBox:
                {
                    if (m_mode == M_client)
                    {
                        writeError(assetErrorFileSkyBox, *warningListIter, totalErrorCountSkyBox);
                    }
                }
                break;
                case AT_slotDescriptor:
                {
                    if (m_mode == M_client)
                    {
                        writeError(assetErrorFileSlotDescriptor, *warningListIter, totalErrorCountSlotDescriptor);
                    }
                }
                break;
                case AT_soundTemplate:
                {
                    if (m_mode == M_client)
                    {
                        writeError(assetErrorFileSoundTemplate, *warningListIter, totalErrorCountSoundTemplate);
                    }
                }
                break;
                case AT_terrain:
                {
                    if (m_mode == M_client)
                    {
                        writeError(assetErrorFileTerrain, *warningListIter, totalErrorCountTerrain);
                    }
                }
                break;
                case AT_texture:
                {
                    if (m_mode == M_client)
                    {
                        writeError(assetErrorFileTexture, *warningListIter, totalErrorCountTexture);
                    }
                }
                break;
                case AT_textureRendererTemplate:
                {
                    if (m_mode == M_client)
                    {
                        writeError(assetErrorFileTextureRenderer, *warningListIter, totalErrorCountTextureRenderer);
                    }
                }
                break;
                default:
                {
                    DEBUG_REPORT_LOG_PRINT(true, ("DataLint::remove() - Unsupported asset type: %s", warningListIter->first.c_str()));
                }
                break;
                }

                // Write the error to the master error file

                writeError(assetErrorFileAll, *warningListIter, totalErrorCountAll);

                // If this is a fatal, write to the fatal list

                if (strstr(warningListIter->first.c_str(), "FATAL:"))
                {
                    writeError(assetErrorFileAllFatal, *warningListIter, totalErrorCountAllFatal);
                }

                // If a warning, write to the warning list

                if (strstr(warningListIter->first.c_str(), "WARNING:"))
                {
                    writeError(assetErrorFileAllWarning, *warningListIter, totalErrorCountAllWarning);
                }
            }
        }

        // UnSupported Assets

        DEBUG_REPORT_LOG_PRINT(true, ("Writing unsupported assets list: %s\n", m_dataLintUnSupportedAssetsFile.c_str()));

        FILE *fp = fopen(m_dataLintUnSupportedAssetsFile.c_str(), "wt");

        if (fp)
        {
            StringPairList unSupportedStringPairList(getList(AT_unSupported));
            StringPairList::iterator stringPairListIter = unSupportedStringPairList.begin();
            int count = 1;

            for (; stringPairListIter != unSupportedStringPairList.end(); ++stringPairListIter)
            {
                fprintf(fp, "%3d %s @ %s\n", count, stringPairListIter->first.c_str(), stringPairListIter->second.c_str());
                ++count;
            }

            fclose(fp);
        }
        else
        {
            DEBUG_REPORT_LOG_PRINT(true, ("Error writing unsupported assets list: %s\n", m_dataLintUnSupportedAssetsFile.c_str()));
        }

        // Categorized Assets

        DEBUG_REPORT_LOG_PRINT(true, ("Writing categorized files list: %s\n", m_dataLintCategorizedAssetsFile.c_str()));

        fp = fopen(m_dataLintCategorizedAssetsFile.c_str(), "wt");

        if (fp)
        {
            fprintf(fp, "This file contains a categorized listing of the linted assets in the game. The categories are as follows:\n");
            fprintf(fp, "\n");
            fprintf(fp, "1.  Appearances                (%5d)\n", getList(AT_appearance).size());
            fprintf(fp, "2.  Arrangement Descriptors    (%5d)\n", getList(AT_arrangementDescriptor).size());
            fprintf(fp, "3.  Localized String Tables    (%5d)\n", getList(AT_localizedStringTable).size());
            fprintf(fp, "4.  Object Templates           (%5d)\n", getList(AT_objectTemplate).size());
            fprintf(fp, "5.  Portal Properties          (%5d)\n", getList(AT_portalProperty).size());
            fprintf(fp, "6.  Shader Templates           (%5d)\n", getList(AT_shaderTemplate).size());
            fprintf(fp, "7.  SkyBoxes                   (%5d)\n", getList(AT_skyBox).size());
            fprintf(fp, "8.  Slot Descriptors           (%5d)\n", getList(AT_slotDescriptor).size());
            fprintf(fp, "9.  Sound Templates            (%5d)\n", getList(AT_soundTemplate).size());
            fprintf(fp, "10. Terrain                    (%5d)\n", getList(AT_terrain).size());
            fprintf(fp, "11. Textures                   (%5d)\n", getList(AT_texture).size());
            fprintf(fp, "12. Texture Renderer Templates (%5d)\n", getList(AT_textureRendererTemplate).size());
            fprintf(fp, "--------------------------------------\n");
            fprintf(fp, "13. Total Linted Assets        (%5d)\n", m_assetList->size() - getList(AT_unSupported).size());
            fprintf(fp, "\n");

            writeToCategorizedFile(fp, "Appearances", AT_appearance);
            writeToCategorizedFile(fp, "Arrangement Descriptors", AT_arrangementDescriptor);
            writeToCategorizedFile(fp, "Localized String Tables", AT_localizedStringTable);
            writeToCategorizedFile(fp, "Object Templates", AT_objectTemplate);
            writeToCategorizedFile(fp, "Portal Properties", AT_portalProperty);
            writeToCategorizedFile(fp, "Shader Templates", AT_shaderTemplate);
            writeToCategorizedFile(fp, "SkyBoxes", AT_skyBox);
            writeToCategorizedFile(fp, "Slot Descriptors", AT_slotDescriptor);
            writeToCategorizedFile(fp, "Sound Templates", AT_soundTemplate);
            writeToCategorizedFile(fp, "Terrain", AT_terrain);
            writeToCategorizedFile(fp, "Textures", AT_texture);
            writeToCategorizedFile(fp, "Texture Renderer Templates", AT_textureRendererTemplate);

            fclose(fp);
        }

        if (assetErrorFileAll) {
            fclose(assetErrorFileAll);
        }
        if (assetErrorFileAllFatal) {
            fclose(assetErrorFileAllFatal);
        }
        if (assetErrorFileAllWarning) {
            fclose(assetErrorFileAllWarning);
        }
        if (assetErrorFileObjectTemplate) {
            fclose(assetErrorFileObjectTemplate);
        }

        if (m_mode == M_client)
        {
            if (assetErrorFileAppearance) {
                fclose(assetErrorFileAppearance);
            }
            if (assetErrorFileArrangementDescriptor) {
                fclose(assetErrorFileArrangementDescriptor);
            }
            if (assetErrorFileLocalizedStringTable) {
                fclose(assetErrorFileLocalizedStringTable);
            }
            if (assetErrorFilePortalProperty) {
                fclose(assetErrorFilePortalProperty);
            }
            if (assetErrorFileShaderTemplate) {
                fclose(assetErrorFileShaderTemplate);
            }
            if (assetErrorFileSkyBox) {
                fclose(assetErrorFileSkyBox);
            }
            if (assetErrorFileSlotDescriptor) {
                fclose(assetErrorFileSlotDescriptor);
            }
            if (assetErrorFileSoundTemplate) {
                fclose(assetErrorFileSoundTemplate);
            }
            if (assetErrorFileTerrain) {
                fclose(assetErrorFileTerrain);
            }
            if (assetErrorFileTexture) {
                fclose(assetErrorFileTexture);
            }
            if (assetErrorFileTextureRenderer) {
                fclose(assetErrorFileTextureRenderer);
            }
        }
    }
}