Logo AND Algorithmique Numérique Distribuée

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