Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
accept single quotes while converting the XML files
[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() {}
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) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); } \
609   catch(...) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); }
610
611 /** @brief Set the value of a variable, using the string representation of that value
612  *
613  * @param key name of the variable to modify
614  * @param value string representation of the value to set
615  */
616
617 void xbt_cfg_set_as_string(const char *key, const char *value)
618 {
619   try {
620     (*simgrid_config)[key].setStringValue(value);
621     return;
622   }
623   TRANSLATE_EXCEPTIONS("Could not set variable %s as string %s", key, value);
624 }
625
626 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
627  *
628  * This is useful to change the default value of a variable while allowing
629  * users to override it with command line arguments
630  */
631 void xbt_cfg_setdefault_int(const char *key, int value)
632 {
633   try {
634     (*simgrid_config)[key].setDefaultValue<int>(value);
635     return;
636   }
637   TRANSLATE_EXCEPTIONS("Could not set variable %s to default integer %i",
638     key, value);
639 }
640
641 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
642  *
643  * This is useful to change the default value of a variable while allowing
644  * users to override it with command line arguments
645  */
646 void xbt_cfg_setdefault_double(const char *key, double value)
647 {
648   try {
649     (*simgrid_config)[key].setDefaultValue<double>(value);
650     return;
651   }
652   TRANSLATE_EXCEPTIONS("Could not set variable %s to default double %f",
653     key, value);
654 }
655
656 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
657  *
658  * This is useful to change the default value of a variable while allowing
659  * users to override it with command line arguments
660  */
661 void xbt_cfg_setdefault_string(const char *key, const char *value)
662 {
663   try {
664     (*simgrid_config)[key].setDefaultValue<std::string>(value ? value : "");
665     return;
666   }
667   TRANSLATE_EXCEPTIONS("Could not set variable %s to default string %s",
668     key, value);
669 }
670
671 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
672  *
673  * This is useful to change the default value of a variable while allowing
674  * users to override it with command line arguments
675  */
676 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
677 {
678   try {
679     (*simgrid_config)[key].setDefaultValue<bool>(simgrid::config::parseBool(value));
680     return;
681   }
682   TRANSLATE_EXCEPTIONS("Could not set variable %s to default boolean %s",
683     key, value);
684 }
685
686 /** @brief Set an integer 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_int(const char *key, int value)
692 {
693   try {
694     (*simgrid_config)[key].setValue<int>(value);
695     return;
696   }
697   TRANSLATE_EXCEPTIONS("Could not set variable %s to integer %i",
698     key, value);
699 }
700
701 /** @brief Set or add a double value to \a name within \a cfg
702  *
703  * @param key the name of the variable
704  * @param value the double to set
705  */
706 void xbt_cfg_set_double(const char *key, double value)
707 {
708   try {
709     (*simgrid_config)[key].setValue<double>(value);
710     return;
711   }
712   TRANSLATE_EXCEPTIONS("Could not set variable %s to double %f",
713     key, value);
714 }
715
716 /** @brief Set or add a string value to \a name within \a cfg
717  *
718  * @param key the name of the variable
719  * @param value the value to be added
720  *
721  */
722 void xbt_cfg_set_string(const char *key, const char *value)
723 {
724   try {
725     (*simgrid_config)[key].setValue<std::string>(value ? value : "");
726     return;
727   }
728   TRANSLATE_EXCEPTIONS("Could not set variable %s to string %s",
729     key, value);
730 }
731
732 /** @brief Set or add a boolean value to \a name within \a cfg
733  *
734  * @param key the name of the variable
735  * @param value the value of the variable
736  */
737 void xbt_cfg_set_boolean(const char *key, const char *value)
738 {
739   try {
740     (*simgrid_config)[key].setValue<bool>(simgrid::config::parseBool(value));
741     return;
742   }
743   TRANSLATE_EXCEPTIONS("Could not set variable %s to boolean %s",
744     key, value);
745 }
746
747
748 /* Say if the value is the default value */
749 int xbt_cfg_is_default_value(const char *key)
750 {
751   try {
752     return (*simgrid_config)[key].isDefault() ? 1 : 0;
753   }
754   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
755 }
756
757 /*----[ Getting ]---------------------------------------------------------*/
758 /** @brief Retrieve an integer 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  */
764 int xbt_cfg_get_int(const char *key)
765 {
766   try {
767     return (*simgrid_config)[key].getValue<int>();
768   }
769   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
770 }
771
772 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
773  *
774  * @param key the name of the variable
775  *
776  * Returns the first value from the config set under the given name.
777  */
778 double xbt_cfg_get_double(const char *key)
779 {
780   try {
781     return (*simgrid_config)[key].getValue<double>();
782   }
783   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
784 }
785
786 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
787  *
788  * @param key the name of the variable
789  *
790  * Returns the first value from the config set under the given name.
791  * If there is more than one value, it will issue a warning.
792  * Returns nullptr if there is no value.
793  *
794  * \warning the returned value is the actual content of the config set
795  */
796 char *xbt_cfg_get_string(const char *key)
797 {
798   try {
799     return (char*) (*simgrid_config)[key].getValue<std::string>().c_str();
800   }
801   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
802 }
803
804 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
805  *
806  * @param key the name of the variable
807  *
808  * Returns the first value from the config set under the given name.
809  * If there is more than one value, it will issue a warning.
810  */
811 int xbt_cfg_get_boolean(const char *key)
812 {
813   try {
814     return (*simgrid_config)[key].getValue<bool>() ? 1 : 0;
815   }
816   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
817 }
818
819 #ifdef SIMGRID_TEST
820
821 #include <string>
822
823 #include "xbt.h"
824 #include "xbt/ex.h"
825
826 #include <xbt/config.hpp>
827
828 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
829
830 XBT_TEST_SUITE("config", "Configuration support");
831
832 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
833
834 static void make_set()
835 {
836   simgrid_config = nullptr;
837   xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
838   xbt_cfg_register_int("speed", 0, nullptr, "");
839   xbt_cfg_register_string("peername", "", nullptr, "");
840   xbt_cfg_register_string("user", "", nullptr, "");
841 }                               /* end_of_make_set */
842
843 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
844 {
845   auto temp = simgrid_config;
846   make_set();
847   xbt_test_add("Alloc and free a config set");
848   xbt_cfg_set_parse("peername:veloce user:bidule");
849   xbt_cfg_free(&simgrid_config);
850   simgrid_config = temp;
851 }
852
853 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
854 {
855   auto temp = simgrid_config;
856   make_set();
857   xbt_test_add("Get a single value");
858   {
859     /* get_single_value */
860     int ival;
861
862     xbt_cfg_set_parse("peername:toto:42 speed:42");
863     ival = xbt_cfg_get_int("speed");
864     if (ival != 42)
865       xbt_test_fail("Speed value = %d, I expected 42", ival);
866   }
867
868   xbt_test_add("Access to a non-existant entry");
869   {
870     try {
871       xbt_cfg_set_parse("color:blue");
872     } catch(xbt_ex& e) {
873       if (e.category != not_found_error)
874         xbt_test_exception(e);
875     }
876   }
877   xbt_cfg_free(&simgrid_config);
878   simgrid_config = temp;
879 }
880
881 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
882 {
883   auto temp = simgrid_config;
884   make_set();
885   xbt_test_add("C++ declaration of flags");
886
887   simgrid::config::Flag<int> int_flag("int", "", 0);
888   simgrid::config::Flag<std::string> string_flag("string", "", "foo");
889   simgrid::config::Flag<double> double_flag("double", "", 0.32);
890   simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
891   simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
892
893   xbt_test_add("Parse values");
894   xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
895   xbt_test_assert(int_flag == 42, "Check int flag");
896   xbt_test_assert(string_flag == "bar", "Check string flag");
897   xbt_test_assert(double_flag == 8.0, "Check double flag");
898   xbt_test_assert(bool_flag1, "Check bool1 flag");
899   xbt_test_assert(!bool_flag2, "Check bool2 flag");
900
901   xbt_cfg_free(&simgrid_config);
902   simgrid_config = temp;
903 }
904
905 #endif                          /* SIMGRID_TEST */