Logo AND Algorithmique Numérique Distribuée

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