Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Define simgrid::xbt::Path to manage file names.
[simgrid.git] / src / xbt / config.cpp
1 /* Copyright (c) 2004-2017. The SimGrid Team. All rights reserved.     */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include <cstdio>
7
8 #include <algorithm>
9 #include <cerrno>
10 #include <cstring>
11 #include <climits>
12
13 #include <functional>
14 #include <map>
15 #include <stdexcept>
16 #include <string>
17 #include <type_traits>
18 #include <typeinfo>
19 #include <vector>
20
21 #include <xbt/ex.hpp>
22 #include <xbt/config.h>
23 #include <xbt/config.hpp>
24 #include "xbt/misc.h"
25 #include "xbt/sysdep.h"
26 #include "xbt/log.h"
27 #include "xbt/dynar.h"
28
29 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
30
31 XBT_EXPORT_NO_IMPORT(xbt_cfg_t) simgrid_config = nullptr;
32 extern "C" {
33   XBT_PUBLIC(void) sg_config_finalize();
34 }
35
36 namespace simgrid {
37 namespace config {
38
39 missing_key_error::~missing_key_error() = default;
40
41 class Config;
42
43 namespace {
44
45 const char* true_values[] = {
46   "yes", "on", "true", "1"
47 };
48 const char* false_values[] = {
49   "no", "off", "false", "0"
50 };
51
52 static bool parseBool(const char* value)
53 {
54   for (const char* const& true_value : true_values)
55     if (std::strcmp(true_value, value) == 0)
56       return true;
57   for (const char* const& false_value : false_values)
58     if (std::strcmp(false_value, value) == 0)
59       return false;
60   throw std::range_error("not a boolean");
61 }
62
63 static double parseDouble(const char* value)
64 {
65   char* end;
66   errno = 0;
67   double res = std::strtod(value, &end);
68   if (errno == ERANGE)
69     throw std::range_error("out of range");
70   else if (errno)
71     xbt_die("Unexpected errno");
72   if (end == value || *end != '\0')
73     throw std::range_error("invalid double");
74   else
75     return res;
76 }
77
78 static long int parseLong(const char* value)
79 {
80   char* end;
81   errno = 0;
82   long int res = std::strtol(value, &end, 0);
83   if (errno) {
84     if (res == LONG_MIN && errno == ERANGE)
85       throw std::range_error("underflow");
86     else if (res == LONG_MAX && errno == ERANGE)
87       throw std::range_error("overflow");
88     xbt_die("Unexpected errno");
89   }
90   if (end == value || *end != '\0')
91     throw std::range_error("invalid integer");
92   else
93     return res;
94 }
95
96 // ***** ConfigType *****
97
98 /// A trait which define possible options types:
99 template <class T> class ConfigType;
100
101 template <> class ConfigType<int> {
102 public:
103   static constexpr const char* type_name = "int";
104   static inline double parse(const char* value)
105   {
106     return parseLong(value);
107   }
108 };
109 template <> class ConfigType<double> {
110 public:
111   static constexpr const char* type_name = "double";
112   static inline double parse(const char* value)
113   {
114     return parseDouble(value);
115   }
116 };
117 template <> class ConfigType<std::string> {
118 public:
119   static constexpr const char* type_name = "string";
120   static inline std::string parse(const char* value)
121   {
122     return std::string(value);
123   }
124 };
125 template <> class ConfigType<bool> {
126 public:
127   static constexpr const char* type_name = "boolean";
128   static inline bool parse(const char* value)
129   {
130     return parseBool(value);
131   }
132 };
133
134 // **** Forward declarations ****
135
136 class ConfigurationElement ;
137 template<class T> class TypedConfigurationElement;
138
139 // **** ConfigurationElement ****
140
141 class ConfigurationElement {
142 private:
143   std::string key;
144   std::string desc;
145   bool isdefault = true;
146
147 public:
148   /* Callback */
149   xbt_cfg_cb_t old_callback = nullptr;
150
151   ConfigurationElement(const char* key, const char* desc)
152     : key(key ? key : ""), desc(desc ? desc : "") {}
153   ConfigurationElement(const char* key, const char* desc, xbt_cfg_cb_t cb)
154     : key(key ? key : ""), desc(desc ? desc : ""), old_callback(cb) {}
155
156   virtual ~ConfigurationElement()=default;
157
158   virtual std::string getStringValue() = 0;
159   virtual void setStringValue(const char* value) = 0;
160   virtual const char* getTypeName() = 0;
161
162   template<class T>
163   T const& getValue() const
164   {
165     return dynamic_cast<const TypedConfigurationElement<T>&>(*this).getValue();
166   }
167   template<class T>
168   void setValue(T value)
169   {
170     dynamic_cast<TypedConfigurationElement<T>&>(*this).setValue(std::move(value));
171   }
172   template<class T>
173   void setDefaultValue(T value)
174   {
175     dynamic_cast<TypedConfigurationElement<T>&>(*this).setDefaultValue(std::move(value));
176   }
177   void unsetDefault() { isdefault = false; }
178   bool isDefault() const { return isdefault; }
179
180   std::string const& getDescription() const { return desc; }
181   std::string const& getKey() const { return key; }
182 };
183
184 // **** TypedConfigurationElement<T> ****
185
186 // TODO, could we use boost::any with some Type* reference?
187 template<class T>
188 class TypedConfigurationElement : public ConfigurationElement {
189 private:
190   T content;
191   std::function<void(T&)> callback;
192
193 public:
194   TypedConfigurationElement(const char* key, const char* desc, T value = T())
195     : ConfigurationElement(key, desc), content(std::move(value))
196   {}
197   TypedConfigurationElement(const char* key, const char* desc, T value, xbt_cfg_cb_t cb)
198       : ConfigurationElement(key, desc, cb), content(std::move(value))
199   {}
200   TypedConfigurationElement(const char* key, const char* desc, T value, std::function<void(T&)> callback)
201       : ConfigurationElement(key, desc), content(std::move(value)), callback(std::move(callback))
202   {}
203   ~TypedConfigurationElement() = default;
204
205   std::string getStringValue() override;
206   const char* getTypeName() override;
207   void setStringValue(const char* value) override;
208
209   void update()
210   {
211     if (old_callback)
212       this->old_callback(getKey().c_str());
213     if (this->callback)
214       this->callback(this->content);
215   }
216
217   T const& getValue() const { return content; }
218
219   void setValue(T value)
220   {
221     this->content = std::move(value);
222     this->update();
223   }
224
225   void setDefaultValue(T value)
226   {
227     if (this->isDefault()) {
228       this->content = std::move(value);
229       this->update();
230     } else {
231       XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.",
232                 getKey().c_str(), to_string(value).c_str());
233     }
234   }
235 };
236
237 template<class T>
238 std::string TypedConfigurationElement<T>::getStringValue() // override
239 {
240   return to_string(content);
241 }
242
243 template<class T>
244 void TypedConfigurationElement<T>::setStringValue(const char* value) // override
245 {
246   this->content = ConfigType<T>::parse(value);
247   this->unsetDefault();
248   this->update();
249 }
250
251 template<class T>
252 const char* TypedConfigurationElement<T>::getTypeName() // override
253 {
254   return ConfigType<T>::type_name;
255 }
256
257 } // end of anonymous namespace
258
259 // **** Config ****
260
261 class Config {
262 private:
263   // name -> ConfigElement:
264   std::map<std::string, simgrid::config::ConfigurationElement*> options;
265   // alias -> xbt_dict_elm_t from options:
266   std::map<std::string, simgrid::config::ConfigurationElement*> aliases;
267   bool warn_for_aliases = true;
268
269 public:
270   Config() = default;
271   ~Config();
272
273   // No copy:
274   Config(Config const&) = delete;
275   Config& operator=(Config const&) = delete;
276
277   ConfigurationElement& operator[](const char* name);
278   template<class T>
279   TypedConfigurationElement<T>& getTyped(const char* name);
280   void alias(const char* realname, const char* aliasname);
281
282   template<class T, class... A>
283   simgrid::config::TypedConfigurationElement<T>*
284     registerOption(const char* name, A&&... a)
285   {
286     xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.", name);
287     TypedConfigurationElement<T>* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
288     XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name, variable->getDescription().c_str(),
289               variable->getTypeName(), variable, this);
290     options.insert({name, variable});
291     variable->update();
292     return variable;
293   }
294
295   // Debug:
296   void dump(const char *name, const char *indent);
297   void showAliases();
298   void help();
299
300 protected:
301   ConfigurationElement* getDictElement(const char* name);
302 };
303
304 Config::~Config()
305 {
306   XBT_DEBUG("Frees cfg set %p", this);
307   for (auto const& elm : options)
308     delete elm.second;
309 }
310
311 inline ConfigurationElement* Config::getDictElement(const char* name)
312 {
313   auto opt = options.find(name);
314   if (opt != options.end()) {
315     return opt->second;
316   } else {
317     auto als = aliases.find(name);
318     if (als != aliases.end()) {
319       ConfigurationElement* res = als->second;
320       if (warn_for_aliases)
321         XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->getKey().c_str());
322       return res;
323     } else {
324       throw simgrid::config::missing_key_error(std::string("Bad config key: ") + name);
325     }
326   }
327 }
328
329 inline ConfigurationElement& Config::operator[](const char* name)
330 {
331   return *(getDictElement(name));
332 }
333
334 void Config::alias(const char* realname, const char* aliasname)
335 {
336   xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname);
337   ConfigurationElement* element = this->getDictElement(realname);
338   xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
339   this->aliases.insert({aliasname, element});
340 }
341
342 /** @brief Dump a config set for debuging purpose
343  *
344  * @param name The name to give to this config set
345  * @param indent what to write at the beginning of each line (right number of spaces)
346  */
347 void Config::dump(const char *name, const char *indent)
348 {
349   if (name)
350     printf("%s>> Dumping of the config set '%s':\n", indent, name);
351
352   for (auto const& elm : options)
353     printf("%s  %s: ()%s) %s", indent, elm.first.c_str(), elm.second->getTypeName(),
354            elm.second->getStringValue().c_str());
355
356   if (name)
357     printf("%s<< End of the config set '%s'\n", indent, name);
358   fflush(stdout);
359 }
360
361 /** @brief Displays the declared aliases and their description */
362 void Config::showAliases()
363 {
364   bool old_warn_for_aliases = false;
365   std::swap(warn_for_aliases, old_warn_for_aliases);
366   for (auto const& elm : aliases)
367     printf("   %s: %s\n", elm.first.c_str(), (*this)[elm.first.c_str()].getDescription().c_str());
368   std::swap(warn_for_aliases, old_warn_for_aliases);
369 }
370
371 /** @brief Displays the declared options and their description */
372 void Config::help()
373 {
374   for (auto const& elm : options) {
375     simgrid::config::ConfigurationElement* variable = this->options.at(elm.first);
376     printf("   %s: %s\n", elm.first.c_str(), variable->getDescription().c_str());
377     printf("       Type: %s; ", variable->getTypeName());
378     printf("Current value: %s\n", variable->getStringValue().c_str());
379   }
380 }
381
382 // ***** getConfig *****
383
384 template<class T>
385 XBT_PUBLIC(T const&) getConfig(const char* name)
386 {
387   return (*simgrid_config)[name].getValue<T>();
388 }
389
390 template XBT_PUBLIC(int const&) getConfig<int>(const char* name);
391 template XBT_PUBLIC(double const&) getConfig<double>(const char* name);
392 template XBT_PUBLIC(bool const&) getConfig<bool>(const char* name);
393 template XBT_PUBLIC(std::string const&) getConfig<std::string>(const char* name);
394
395 // ***** alias *****
396
397 void alias(const char* realname, const char* aliasname)
398 {
399   simgrid_config->alias(realname, aliasname);
400 }
401
402 // ***** declareFlag *****
403
404 template<class T>
405 XBT_PUBLIC(void) declareFlag(const char* name, const char* description,
406   T value, std::function<void(const T&)> callback)
407 {
408   if (simgrid_config == nullptr) {
409     simgrid_config = xbt_cfg_new();
410     atexit(sg_config_finalize);
411   }
412   simgrid_config->registerOption<T>(
413     name, description, std::move(value), std::move(callback));
414 }
415
416 template XBT_PUBLIC(void) declareFlag(const char* name,
417   const char* description, int value, std::function<void(int const &)> callback);
418 template XBT_PUBLIC(void) declareFlag(const char* name,
419   const char* description, double value, std::function<void(double const &)> callback);
420 template XBT_PUBLIC(void) declareFlag(const char* name,
421   const char* description, bool value, std::function<void(bool const &)> callback);
422 template XBT_PUBLIC(void) declareFlag(const char* name,
423   const char* description, std::string value, std::function<void(std::string const &)> callback);
424
425 }
426 }
427
428 // ***** C bindings *****
429
430 xbt_cfg_t xbt_cfg_new()        { return new simgrid::config::Config(); }
431 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
432
433 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
434 {
435   cfg->dump(name, indent);
436 }
437
438 /*----[ Registering stuff ]-----------------------------------------------*/
439
440 void xbt_cfg_register_double(const char *name, double default_value,
441   xbt_cfg_cb_t cb_set, const char *desc)
442 {
443   if (simgrid_config == nullptr)
444     simgrid_config = xbt_cfg_new();
445   simgrid_config->registerOption<double>(name, desc, default_value, cb_set);
446 }
447
448 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
449 {
450   if (simgrid_config == nullptr) {
451     simgrid_config = xbt_cfg_new();
452     atexit(&sg_config_finalize);
453   }
454   simgrid_config->registerOption<int>(name, desc, default_value, cb_set);
455 }
456
457 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
458 {
459   if (simgrid_config == nullptr) {
460     simgrid_config = xbt_cfg_new();
461     atexit(sg_config_finalize);
462   }
463   simgrid_config->registerOption<std::string>(name, desc,
464     default_value ? default_value : "", cb_set);
465 }
466
467 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
468 {
469   if (simgrid_config == nullptr) {
470     simgrid_config = xbt_cfg_new();
471     atexit(sg_config_finalize);
472   }
473   simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
474 }
475
476 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
477 {
478   if (simgrid_config == nullptr) {
479     simgrid_config = xbt_cfg_new();
480     atexit(sg_config_finalize);
481   }
482   simgrid_config->alias(realname, aliasname);
483 }
484
485 void xbt_cfg_aliases() { simgrid_config->showAliases(); }
486 void xbt_cfg_help()    { simgrid_config->help(); }
487
488 /*----[ Setting ]---------------------------------------------------------*/
489
490 /** @brief Add values parsed from a string into a config set
491  *
492  * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
493  * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
494  * already registered variable, and [value] conforms to the data type under which this variable was registered.
495  *
496  * @todo This is a crude manual parser, it should be a proper lexer.
497  */
498 void xbt_cfg_set_parse(const char *options)
499 {
500   if (not options || not strlen(options)) { /* nothing to do */
501     return;
502   }
503   char *optionlist_cpy = xbt_strdup(options);
504
505   XBT_DEBUG("List to parse and set:'%s'", options);
506   char *option = optionlist_cpy;
507   while (1) {                   /* breaks in the code */
508     if (not option)
509       break;
510     char *name = option;
511     int len = strlen(name);
512     XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
513
514     /* Pass the value */
515     while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
516       XBT_DEBUG("Take %c.", *option);
517       option++;
518     }
519     if (option - name == len) {
520       XBT_DEBUG("Boundary=EOL");
521       option = nullptr;            /* don't do next iteration */
522     } else {
523       XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
524       /* Pass the following blank chars */
525       *(option++) = '\0';
526       while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
527         option++;
528       }
529       if (option - name == len - 1)
530         option = nullptr;          /* don't do next iteration */
531     }
532     XBT_DEBUG("parse now:'%s'; parse later:'%s'", name, option);
533
534     if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
535       continue;
536     if (not strlen(name))
537       break;
538
539     char *val = strchr(name, ':');
540     xbt_assert(val, "Option '%s' badly formatted. Should be of the form 'name:value'", name);
541     /* don't free(optionlist_cpy) if the assert fails, 'name' points inside it */
542     *(val++) = '\0';
543
544     if (strncmp(name, "path", strlen("path")))
545       XBT_INFO("Configuration change: Set '%s' to '%s'", name, val);
546
547     try {
548       (*simgrid_config)[name].setStringValue(val);
549     }
550     catch (simgrid::config::missing_key_error& e) {
551       goto on_missing_key;
552     }
553     catch (...) {
554       goto on_exception;
555     }
556   }
557
558   free(optionlist_cpy);
559   return;
560
561   /* Do not THROWF from a C++ exception catching context, or some cleanups will be missing */
562 on_missing_key:
563   free(optionlist_cpy);
564   THROWF(not_found_error, 0, "Could not set variables %s", options);
565   return;
566 on_exception:
567   free(optionlist_cpy);
568   THROWF(unknown_error, 0, "Could not set variables %s", options);
569 }
570
571 // Horrible mess to translate C++ exceptions to C exceptions:
572 // Exit from the catch block (and do the correct exception cleaning) before attempting to THROWF.
573 #define TRANSLATE_EXCEPTIONS(...) \
574   catch(simgrid::config::missing_key_error& e) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); } \
575   catch(...) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); }
576
577 /** @brief Set the value of a variable, using the string representation of that value
578  *
579  * @param key name of the variable to modify
580  * @param value string representation of the value to set
581  */
582
583 void xbt_cfg_set_as_string(const char *key, const char *value)
584 {
585   try {
586     (*simgrid_config)[key].setStringValue(value);
587     return;
588   }
589   TRANSLATE_EXCEPTIONS("Could not set variable %s as string %s", key, value);
590 }
591
592 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
593  *
594  * This is useful to change the default value of a variable while allowing
595  * users to override it with command line arguments
596  */
597 void xbt_cfg_setdefault_int(const char *key, int value)
598 {
599   try {
600     (*simgrid_config)[key].setDefaultValue<int>(value);
601     return;
602   }
603   TRANSLATE_EXCEPTIONS("Could not set variable %s to default integer %i", key, value);
604 }
605
606 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
607  *
608  * This is useful to change the default value of a variable while allowing
609  * users to override it with command line arguments
610  */
611 void xbt_cfg_setdefault_double(const char *key, double value)
612 {
613   try {
614     (*simgrid_config)[key].setDefaultValue<double>(value);
615     return;
616   }
617   TRANSLATE_EXCEPTIONS("Could not set variable %s to default double %f", key, value);
618 }
619
620 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
621  *
622  * This is useful to change the default value of a variable while allowing
623  * users to override it with command line arguments
624  */
625 void xbt_cfg_setdefault_string(const char *key, const char *value)
626 {
627   try {
628     (*simgrid_config)[key].setDefaultValue<std::string>(value ? value : "");
629     return;
630   }
631   TRANSLATE_EXCEPTIONS("Could not set variable %s to default string %s", key, value);
632 }
633
634 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
635  *
636  * This is useful to change the default value of a variable while allowing
637  * users to override it with command line arguments
638  */
639 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
640 {
641   try {
642     (*simgrid_config)[key].setDefaultValue<bool>(simgrid::config::parseBool(value));
643     return;
644   }
645   TRANSLATE_EXCEPTIONS("Could not set variable %s to default boolean %s", key, value);
646 }
647
648 /** @brief Set an integer value to \a name within \a cfg
649  *
650  * @param key the name of the variable
651  * @param value the value of the variable
652  */
653 void xbt_cfg_set_int(const char *key, int value)
654 {
655   try {
656     (*simgrid_config)[key].setValue<int>(value);
657     return;
658   }
659   TRANSLATE_EXCEPTIONS("Could not set variable %s to integer %i", key, value);
660 }
661
662 /** @brief Set or add a double value to \a name within \a cfg
663  *
664  * @param key the name of the variable
665  * @param value the double to set
666  */
667 void xbt_cfg_set_double(const char *key, double value)
668 {
669   try {
670     (*simgrid_config)[key].setValue<double>(value);
671     return;
672   }
673   TRANSLATE_EXCEPTIONS("Could not set variable %s to double %f", key, value);
674 }
675
676 /** @brief Set or add a string value to \a name within \a cfg
677  *
678  * @param key the name of the variable
679  * @param value the value to be added
680  *
681  */
682 void xbt_cfg_set_string(const char *key, const char *value)
683 {
684   try {
685     (*simgrid_config)[key].setValue<std::string>(value ? value : "");
686     return;
687   }
688   TRANSLATE_EXCEPTIONS("Could not set variable %s to string %s", key, value);
689 }
690
691 /** @brief Set or add a boolean value to \a name within \a cfg
692  *
693  * @param key the name of the variable
694  * @param value the value of the variable
695  */
696 void xbt_cfg_set_boolean(const char *key, const char *value)
697 {
698   try {
699     (*simgrid_config)[key].setValue<bool>(simgrid::config::parseBool(value));
700     return;
701   }
702   TRANSLATE_EXCEPTIONS("Could not set variable %s to boolean %s", key, value);
703 }
704
705
706 /* Say if the value is the default value */
707 int xbt_cfg_is_default_value(const char *key)
708 {
709   try {
710     return (*simgrid_config)[key].isDefault() ? 1 : 0;
711   }
712   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
713 }
714
715 /*----[ Getting ]---------------------------------------------------------*/
716 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
717  *
718  * @param key the name of the variable
719  *
720  * Returns the first value from the config set under the given name.
721  */
722 int xbt_cfg_get_int(const char *key)
723 {
724   try {
725     return (*simgrid_config)[key].getValue<int>();
726   }
727   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
728 }
729
730 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
731  *
732  * @param key the name of the variable
733  *
734  * Returns the first value from the config set under the given name.
735  */
736 double xbt_cfg_get_double(const char *key)
737 {
738   try {
739     return (*simgrid_config)[key].getValue<double>();
740   }
741   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
742 }
743
744 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
745  *
746  * @param key the name of the variable
747  *
748  * Returns the first value from the config set under the given name.
749  * If there is more than one value, it will issue a warning.
750  * Returns nullptr if there is no value.
751  *
752  * \warning the returned value is the actual content of the config set
753  */
754 char *xbt_cfg_get_string(const char *key)
755 {
756   try {
757     return (char*) (*simgrid_config)[key].getValue<std::string>().c_str();
758   }
759   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
760 }
761
762 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
763  *
764  * @param key the name of the variable
765  *
766  * Returns the first value from the config set under the given name.
767  * If there is more than one value, it will issue a warning.
768  */
769 int xbt_cfg_get_boolean(const char *key)
770 {
771   try {
772     return (*simgrid_config)[key].getValue<bool>() ? 1 : 0;
773   }
774   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
775 }
776
777 #ifdef SIMGRID_TEST
778
779 #include <string>
780
781 #include "xbt.h"
782 #include "xbt/ex.h"
783 #include <xbt/ex.hpp>
784
785 #include <xbt/config.hpp>
786
787 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
788
789 XBT_TEST_SUITE("config", "Configuration support");
790
791 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
792
793 static void make_set()
794 {
795   simgrid_config = nullptr;
796   xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
797   xbt_cfg_register_int("speed", 0, nullptr, "");
798   xbt_cfg_register_string("peername", "", nullptr, "");
799   xbt_cfg_register_string("user", "", nullptr, "");
800 }                               /* end_of_make_set */
801
802 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
803 {
804   auto temp = simgrid_config;
805   make_set();
806   xbt_test_add("Alloc and free a config set");
807   xbt_cfg_set_parse("peername:veloce user:bidule");
808   xbt_cfg_free(&simgrid_config);
809   simgrid_config = temp;
810 }
811
812 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
813 {
814   auto temp = simgrid_config;
815   make_set();
816   xbt_test_add("Get a single value");
817   {
818     /* get_single_value */
819     xbt_cfg_set_parse("peername:toto:42 speed:42");
820     int ival = xbt_cfg_get_int("speed");
821     if (ival != 42)
822       xbt_test_fail("Speed value = %d, I expected 42", ival);
823   }
824
825   xbt_test_add("Access to a non-existant entry");
826   {
827     try {
828       xbt_cfg_set_parse("color:blue");
829     } catch(xbt_ex& e) {
830       if (e.category != not_found_error)
831         xbt_test_exception(e);
832     }
833   }
834   xbt_cfg_free(&simgrid_config);
835   simgrid_config = temp;
836 }
837
838 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
839 {
840   auto temp = simgrid_config;
841   make_set();
842   xbt_test_add("C++ declaration of flags");
843
844   simgrid::config::Flag<int> int_flag("int", "", 0);
845   simgrid::config::Flag<std::string> string_flag("string", "", "foo");
846   simgrid::config::Flag<double> double_flag("double", "", 0.32);
847   simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
848   simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
849
850   xbt_test_add("Parse values");
851   xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
852   xbt_test_assert(int_flag == 42, "Check int flag");
853   xbt_test_assert(string_flag == "bar", "Check string flag");
854   xbt_test_assert(double_flag == 8.0, "Check double flag");
855   xbt_test_assert(bool_flag1, "Check bool1 flag");
856   xbt_test_assert(not bool_flag2, "Check bool2 flag");
857
858   xbt_cfg_free(&simgrid_config);
859   simgrid_config = temp;
860 }
861
862 #endif                          /* SIMGRID_TEST */