1 /* Copyright (c) 2004-2014,2016. The SimGrid Team.
2 * All rights reserved. */
14 #include <type_traits>
16 #include <xbt/config.h>
17 #include <xbt/config.hpp>
19 #include "xbt/sysdep.h"
22 #include "xbt/dynar.h"
27 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
29 XBT_EXPORT_NO_IMPORT(xbt_cfg_t) simgrid_config = NULL;
38 const char* true_values[] = {
39 "yes", "on", "true", "1"
41 const char* false_values[] = {
42 "no", "off", "false", "0"
45 static bool parseBool(const char* value)
47 for (const char* true_value : true_values)
48 if (std::strcmp(true_value, value) == 0)
50 for (const char* false_value : false_values)
51 if (std::strcmp(false_value, value) == 0)
53 throw std::domain_error("not a boolean");
56 static double parseDouble(const char* value)
60 double res = std::strtod(value, &end);
62 throw std::range_error("out of range");
64 xbt_die("Unexpected errno");
65 if (end == value || *end != '\0')
66 throw std::range_error("invalid double");
71 static long int parseLong(const char* value)
75 long int res = std::strtol(value, &end, 0);
77 if (res == LONG_MIN && errno == ERANGE)
78 throw std::range_error("underflow");
79 else if (res == LONG_MAX && errno == ERANGE)
80 throw std::range_error("overflow");
81 xbt_die("Unexpected errno");
83 if (end == value || *end != '\0')
84 throw std::range_error("invalid integer");
89 // ***** ConfigType *****
91 /// A trait which define possible options types:
92 template<class T> struct ConfigType;
94 template<> struct ConfigType<int> {
95 static constexpr const char* type_name = "int";
96 static inline double parse(const char* value)
98 return parseLong(value);
101 template<> struct ConfigType<double> {
102 static constexpr const char* type_name = "double";
103 static inline double parse(const char* value)
105 return parseDouble(value);
108 template<> struct ConfigType<std::string> {
109 static constexpr const char* type_name = "string";
110 static inline std::string parse(const char* value)
112 return std::string(value);
115 template<> struct ConfigType<bool> {
116 static constexpr const char* type_name = "boolean";
117 static inline bool parse(const char* value)
119 return parseBool(value);
123 // **** Forward declarations ****
125 class ConfigurationElement ;
126 template<class T> class TypedConfigurationElement;
128 // **** ConfigurationElement ****
130 class ConfigurationElement {
134 bool isdefault = true;
139 xbt_cfg_cb_t old_callback = nullptr;
141 ConfigurationElement(const char* key, const char* desc)
142 : key(key ? key : ""), desc(desc ? desc : "") {}
143 ConfigurationElement(const char* key, const char* desc, xbt_cfg_cb_t cb)
144 : key(key ? key : ""), desc(desc ? desc : ""), old_callback(cb) {}
146 virtual ~ConfigurationElement();
148 virtual std::string getStringValue() = 0;
149 virtual void setStringValue(const char* value) = 0;
150 virtual const char* getTypeName() = 0;
153 T const& getValue() const
155 return dynamic_cast<const TypedConfigurationElement<T>&>(*this).getValue();
158 void setValue(T value)
160 dynamic_cast<TypedConfigurationElement<T>&>(*this).setValue(std::move(value));
163 void setDefaultValue(T value)
165 dynamic_cast<TypedConfigurationElement<T>&>(*this).setDefaultValue(std::move(value));
167 bool isDefault() const { return isdefault; }
169 std::string const& getDescription() const { return desc; }
172 ConfigurationElement::~ConfigurationElement() {}
174 // **** TypedConfigurationElement<T> ****
176 // TODO, could we use boost::any with some Type* reference?
178 class TypedConfigurationElement : public ConfigurationElement {
181 std::function<void(T&)> callback;
184 TypedConfigurationElement(const char* key, const char* desc, T value = T())
185 : ConfigurationElement(key, desc), content(std::move(value))
187 TypedConfigurationElement(const char* key, const char* desc, T value,
189 : ConfigurationElement(key, desc, cb), content(std::move(value))
191 TypedConfigurationElement(const char* key, const char* desc, T value,
192 std::function<void(T&)> callback)
193 : ConfigurationElement(key, desc), content(std::move(value)),
194 callback(std::move(callback))
196 ~TypedConfigurationElement() override;
198 std::string getStringValue() override;
199 const char* getTypeName() override;
200 void setStringValue(const char* value) override;
205 this->old_callback(key.c_str());
207 this->callback(this->content);
210 T const& getValue() const { return content; }
212 void setValue(T value)
214 this->content = std::move(value);
218 void setDefaultValue(T value)
220 if (this->isdefault) {
221 this->content = std::move(value);
224 XBT_DEBUG("Do not override configuration variable '%s' with value '%s'"
225 " because it was already set.", key.c_str(), to_string(value).c_str());
231 std::string TypedConfigurationElement<T>::getStringValue() // override
233 return to_string(content);
237 void TypedConfigurationElement<T>::setStringValue(const char* value) // override
239 this->content = ConfigType<T>::parse(value);
240 this->isdefault = false;
245 const char* TypedConfigurationElement<T>::getTypeName() // override
247 return ConfigType<T>::type_name;
251 TypedConfigurationElement<T>::~TypedConfigurationElement()
254 } // end of anonymous namespace
260 // name -> ConfigElement:
262 // alias -> xbt_dict_elm_t from options:
270 Config(Config const&) = delete;
271 Config& operator=(Config const&) = delete;
273 ConfigurationElement& operator[](const char* name);
275 TypedConfigurationElement<T>& getTyped(const char* name);
276 void alias(const char* realname, const char* aliasname);
278 template<class T, class... A>
279 simgrid::config::TypedConfigurationElement<T>*
280 registerOption(const char* name, A&&... a)
282 xbt_assert(xbt_dict_get_or_null(this->options, name) == nullptr,
283 "Refusing to register the config element '%s' twice.", name);
284 TypedConfigurationElement<T>* variable =
285 new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
286 XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)",
288 variable->getDescription().c_str(),
289 variable->getTypeName(), variable, this);
290 xbt_dict_set(this->options, name, variable, NULL);
296 void dump(const char *name, const char *indent);
301 xbt_dictelm_t getDictElement(const char* name);
304 /* Internal stuff used in cache to free a variable */
305 static void xbt_cfgelm_free(void *data)
308 delete (simgrid::config::ConfigurationElement*) data;
312 options(xbt_dict_new_homogeneous(xbt_cfgelm_free)),
313 aliases(xbt_dict_new_homogeneous(NULL))
318 XBT_DEBUG("Frees cfg set %p", this);
319 xbt_dict_free(&this->options);
320 xbt_dict_free(&this->aliases);
324 xbt_dictelm_t Config::getDictElement(const char* name)
326 // We are interested in the options dictelm:
327 xbt_dictelm_t res = xbt_dict_get_elm_or_null(options, name);
330 // The aliases dict stores pointers to the options dictelm:
331 res = (xbt_dictelm_t) xbt_dict_get_or_null(aliases, name);
333 XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->key);
338 ConfigurationElement& Config::operator[](const char* name)
340 xbt_dictelm_t elm = getDictElement(name);
342 throw std::invalid_argument(std::string("Bad config key, ") + name);
343 return *(ConfigurationElement*)elm->content;
346 void Config::alias(const char* realname, const char* aliasname)
348 xbt_assert(this->getDictElement(aliasname) == nullptr, "Alias '%s' already.", aliasname);
349 xbt_dictelm_t element = this->getDictElement(realname);
350 xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
351 xbt_dict_set(this->aliases, aliasname, element, NULL);
354 /** @brief Dump a config set for debuging purpose
356 * @param name The name to give to this config set
357 * @param indent what to write at the beginning of each line (right number of spaces)
359 void Config::dump(const char *name, const char *indent)
361 xbt_dict_t dict = this->options;
362 xbt_dict_cursor_t cursor = NULL;
363 simgrid::config::ConfigurationElement* variable = NULL;
367 printf("%s>> Dumping of the config set '%s':\n", indent, name);
369 xbt_dict_foreach(dict, cursor, key, variable)
370 printf("%s %s: ()%s) %s", indent, key,
371 variable->getTypeName(),
372 variable->getStringValue().c_str());
375 printf("%s<< End of the config set '%s'\n", indent, name);
378 xbt_dict_cursor_free(&cursor);
381 /** @brief Displays the declared aliases and their description */
382 void Config::showAliases()
384 xbt_dict_cursor_t dict_cursor;
385 unsigned int dynar_cursor;
386 xbt_dictelm_t dictel;
388 xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
390 xbt_dict_foreach(this->aliases, dict_cursor, name, dictel)
391 xbt_dynar_push(names, &name);
392 xbt_dynar_sort_strings(names);
394 xbt_dynar_foreach(names, dynar_cursor, name)
395 printf(" %s: %s\n", name, (*this)[name].getDescription().c_str());
398 /** @brief Displays the declared options and their description */
401 xbt_dict_cursor_t dict_cursor;
402 unsigned int dynar_cursor;
403 simgrid::config::ConfigurationElement* variable;
405 xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
407 xbt_dict_foreach(this->options, dict_cursor, name, variable)
408 xbt_dynar_push(names, &name);
409 xbt_dynar_sort_strings(names);
411 xbt_dynar_foreach(names, dynar_cursor, name) {
412 variable = (simgrid::config::ConfigurationElement*) xbt_dict_get(this->options, name);
413 printf(" %s: %s\n", name, variable->getDescription().c_str());
414 printf(" Type: %s; ", variable->getTypeName());
415 printf("Current value: %s\n", variable->getStringValue().c_str());
417 xbt_dynar_free(&names);
420 // ***** getConfig *****
423 XBT_PUBLIC(T const&) getConfig(const char* name)
425 return (*simgrid_config)[name].getValue<T>();
428 template XBT_PUBLIC(int const&) getConfig<int>(const char* name);
429 template XBT_PUBLIC(double const&) getConfig<double>(const char* name);
430 template XBT_PUBLIC(bool const&) getConfig<bool>(const char* name);
431 template XBT_PUBLIC(std::string const&) getConfig<std::string>(const char* name);
435 void alias(const char* realname, const char* aliasname)
437 simgrid_config->alias(realname, aliasname);
440 // ***** declareFlag *****
443 XBT_PUBLIC(void) declareFlag(const char* name, const char* description,
444 T value, std::function<void(const T&)> callback)
446 if (simgrid_config == NULL)
447 simgrid_config = xbt_cfg_new();
448 simgrid_config->registerOption<T>(
449 name, description, std::move(value), std::move(callback));
452 template XBT_PUBLIC(void) declareFlag(const char* name,
453 const char* description, int value, std::function<void(int const &)> callback);
454 template XBT_PUBLIC(void) declareFlag(const char* name,
455 const char* description, double value, std::function<void(double const &)> callback);
456 template XBT_PUBLIC(void) declareFlag(const char* name,
457 const char* description, bool value, std::function<void(bool const &)> callback);
458 template XBT_PUBLIC(void) declareFlag(const char* name,
459 const char* description, std::string value, std::function<void(std::string const &)> callback);
464 // ***** C bindings *****
466 xbt_cfg_t xbt_cfg_new(void) { return new simgrid::config::Config(); }
467 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
469 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
471 cfg->dump(name, indent);
474 /*----[ Registering stuff ]-----------------------------------------------*/
476 void xbt_cfg_register_double(const char *name, double default_value,
477 xbt_cfg_cb_t cb_set, const char *desc)
479 if (simgrid_config == NULL)
480 simgrid_config = xbt_cfg_new();
481 simgrid_config->registerOption<double>(name, desc, default_value, cb_set);
484 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
486 if (simgrid_config == NULL)
487 simgrid_config = xbt_cfg_new();
488 simgrid_config->registerOption<int>(name, desc, default_value, cb_set);
491 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
493 if (simgrid_config == NULL)
494 simgrid_config = xbt_cfg_new();
495 simgrid_config->registerOption<std::string>(name, desc,
496 default_value ? default_value : "", cb_set);
499 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
501 if (simgrid_config == NULL)
502 simgrid_config = xbt_cfg_new();
503 simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
506 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
508 if (simgrid_config == NULL)
509 simgrid_config = xbt_cfg_new();
510 simgrid_config->alias(realname, aliasname);
513 void xbt_cfg_aliases(void) { simgrid_config->showAliases(); }
514 void xbt_cfg_help(void) { simgrid_config->help(); }
516 /*----[ Setting ]---------------------------------------------------------*/
518 /** @brief Add values parsed from a string into a config set
520 * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
521 * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
522 * already registered variable, and [value] conforms to the data type under which this variable was registered.
524 * @todo This is a crude manual parser, it should be a proper lexer.
526 void xbt_cfg_set_parse(const char *options)
528 if (!options || !strlen(options)) { /* nothing to do */
531 char *optionlist_cpy = xbt_strdup(options);
533 XBT_DEBUG("List to parse and set:'%s'", options);
534 char *option = optionlist_cpy;
535 while (1) { /* breaks in the code */
539 int len = strlen(name);
540 XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
543 while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
544 XBT_DEBUG("Take %c.", *option);
547 if (option - name == len) {
548 XBT_DEBUG("Boundary=EOL");
549 option = NULL; /* don't do next iteration */
551 XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
552 /* Pass the following blank chars */
554 while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
555 /* fprintf(stderr,"Ignore a blank char.\n"); */
558 if (option - name == len - 1)
559 option = NULL; /* don't do next iteration */
561 XBT_DEBUG("parse now:'%s'; parse later:'%s'", name, option);
563 if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
568 char *val = strchr(name, ':');
569 xbt_assert(val, "Option '%s' badly formatted. Should be of the form 'name:value'", name);
570 /* don't free(optionlist_cpy) if the assert fails, 'name' points inside it */
573 if (strncmp(name, "contexts/", strlen("contexts/")) && strncmp(name, "path", strlen("path")))
574 XBT_INFO("Configuration change: Set '%s' to '%s'", name, val);
577 (*simgrid_config)[name].setStringValue(val);
580 THROWF(not_found_error, 0, "Could not set the value %s for %s", val, name);
584 free(optionlist_cpy);
587 /** @brief Set the value of a variable, using the string representation of that value
589 * @param key name of the variable to modify
590 * @param value string representation of the value to set
593 void xbt_cfg_set_as_string(const char *key, const char *value)
596 (*simgrid_config)[key].setStringValue(value);
598 catch (std::exception const& e) {
599 THROWF(unknown_error, 0, "%s", e.what());
603 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
605 * This is useful to change the default value of a variable while allowing
606 * users to override it with command line arguments
608 void xbt_cfg_setdefault_int(const char *name, int val)
611 (*simgrid_config)[name].setDefaultValue<int>(val);
613 catch (std::exception const& e) {
614 THROWF(unknown_error, 0, "%s", e.what());
618 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
620 * This is useful to change the default value of a variable while allowing
621 * users to override it with command line arguments
623 void xbt_cfg_setdefault_double(const char *name, double val)
626 (*simgrid_config)[name].setDefaultValue<double>(val);
628 catch (std::exception const& e) {
629 THROWF(unknown_error, 0, "%s", e.what());
633 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
635 * This is useful to change the default value of a variable while allowing
636 * users to override it with command line arguments
638 void xbt_cfg_setdefault_string(const char *name, const char *val)
641 (*simgrid_config)[name].setDefaultValue<std::string>(val ? val : "");
643 catch (std::exception const& e) {
644 THROWF(unknown_error, 0, "%s", e.what());
648 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
650 * This is useful to change the default value of a variable while allowing
651 * users to override it with command line arguments
653 void xbt_cfg_setdefault_boolean(const char *name, const char *val)
656 (*simgrid_config)[name].setDefaultValue<bool>(simgrid::config::parseBool(val));
658 catch (std::exception const& e) {
659 THROWF(unknown_error, 0, "%s", e.what());
663 /** @brief Set an integer value to \a name within \a cfg
665 * @param name the name of the variable
666 * @param val the value of the variable
668 void xbt_cfg_set_int(const char *name, int val)
671 (*simgrid_config)[name].setValue<int>(val);
673 catch (std::exception const& e) {
674 THROWF(unknown_error, 0, "%s", e.what());
678 /** @brief Set or add a double value to \a name within \a cfg
680 * @param name the name of the variable
681 * @param val the double to set
683 void xbt_cfg_set_double(const char *name, double val)
686 (*simgrid_config)[name].setValue<double>(val);
688 catch (std::exception const& e) {
689 THROWF(unknown_error, 0, "%s", e.what());
693 /** @brief Set or add a string value to \a name within \a cfg
695 * @param cfg the config set
696 * @param name the name of the variable
697 * @param val the value to be added
700 void xbt_cfg_set_string(const char *name, const char *val)
703 (*simgrid_config)[name].setValue<std::string>(val ? val : "");
705 catch (std::exception const& e) {
706 THROWF(unknown_error, 0, "%s", e.what());
710 /** @brief Set or add a boolean value to \a name within \a cfg
712 * @param name the name of the variable
713 * @param val the value of the variable
715 void xbt_cfg_set_boolean(const char *name, const char *val)
718 (*simgrid_config)[name].setValue<bool>(simgrid::config::parseBool(val));
720 catch (std::exception const& e) {
721 THROWF(unknown_error, 0, "%s", e.what());
726 /* Say if the value is the default value */
727 int xbt_cfg_is_default_value(const char *name)
730 return (*simgrid_config)[name].isDefault() ? 1 : 0;
732 catch (std::exception const& e) {
733 THROWF(unknown_error, 0, "%s", e.what());
737 /*----[ Getting ]---------------------------------------------------------*/
738 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
740 * @param name the name of the variable
742 * Returns the first value from the config set under the given name.
744 int xbt_cfg_get_int(const char *name)
747 return (*simgrid_config)[name].getValue<int>();
749 catch (std::exception const& e) {
750 THROWF(unknown_error, 0, "%s", e.what());
754 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
756 * @param cfg the config set
757 * @param name the name of the variable
759 * Returns the first value from the config set under the given name.
761 double xbt_cfg_get_double(const char *name)
764 return (*simgrid_config)[name].getValue<double>();
766 catch (std::exception const& e) {
767 THROWF(unknown_error, 0, "%s", e.what());
771 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
773 * @param cfg the config set
774 * @param name the name of the variable
776 * Returns the first value from the config set under the given name.
777 * If there is more than one value, it will issue a warning.
778 * Returns NULL if there is no value.
780 * \warning the returned value is the actual content of the config set
782 char *xbt_cfg_get_string(const char *name)
785 return (char*) (*simgrid_config)[name].getValue<std::string>().c_str();
787 catch (std::exception const& e) {
788 THROWF(unknown_error, 0, "%s", e.what());
792 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
794 * @param cfg the config set
795 * @param name the name of the variable
797 * Returns the first value from the config set under the given name.
798 * If there is more than one value, it will issue a warning.
800 int xbt_cfg_get_boolean(const char *name)
803 return (*simgrid_config)[name].getValue<bool>() ? 1 : 0;
805 catch (std::exception const& e) {
806 THROWF(unknown_error, 0, "%s", e.what());
817 #include <xbt/config.hpp>
819 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
821 XBT_TEST_SUITE("config", "Configuration support");
823 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
825 static void make_set()
827 simgrid_config = NULL;
828 xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
829 xbt_cfg_register_int("speed", 0, NULL, "");
830 xbt_cfg_register_string("peername", "", NULL, "");
831 xbt_cfg_register_string("user", "", NULL, "");
832 } /* end_of_make_set */
834 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
836 auto temp = simgrid_config;
838 xbt_test_add("Alloc and free a config set");
839 xbt_cfg_set_parse("peername:veloce user:bidule");
840 xbt_cfg_free(&simgrid_config);
841 simgrid_config = temp;
844 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
846 auto temp = simgrid_config;
848 xbt_test_add("Get a single value");
850 /* get_single_value */
853 xbt_cfg_set_parse("peername:toto:42 speed:42");
854 ival = xbt_cfg_get_int("speed");
856 xbt_test_fail("Speed value = %d, I expected 42", ival);
859 xbt_test_add("Access to a non-existant entry");
864 xbt_cfg_set_parse("color:blue");
866 if (e.category != not_found_error)
867 xbt_test_exception(e);
871 xbt_cfg_free(&simgrid_config);
872 simgrid_config = temp;
875 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
877 auto temp = simgrid_config;
879 xbt_test_add("C++ declaration of flags");
881 simgrid::config::Flag<int> int_flag("int", "", 0);
882 simgrid::config::Flag<std::string> string_flag("string", "", "foo");
883 simgrid::config::Flag<double> double_flag("double", "", 0.32);
884 simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
885 simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
887 xbt_test_add("Parse values");
888 xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
889 xbt_test_assert(int_flag == 42, "Check int flag");
890 xbt_test_assert(string_flag == "bar", "Check string flag");
891 xbt_test_assert(double_flag == 8.0, "Check double flag");
892 xbt_test_assert(bool_flag1, "Check bool1 flag");
893 xbt_test_assert(!bool_flag2, "Check bool2 flag");
895 xbt_cfg_free(&simgrid_config);
896 simgrid_config = temp;
899 #endif /* SIMGRID_TEST */