Logo AND Algorithmique Numérique Distribuée

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