Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[config] Create a Config class
[simgrid.git] / src / xbt / config.cpp
1 /* Copyright (c) 2004-2014,2016. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 #include <stdio.h>
5
6 #include <cerrno>
7 #include <cstring>
8 #include <climits>
9 #include <functional>
10 #include <stdexcept>
11 #include <string>
12 #include <type_traits>
13
14 #include <xbt/config.h>
15 #include <xbt/config.hpp>
16 #include "xbt/misc.h"
17 #include "xbt/sysdep.h"
18 #include "xbt/log.h"
19 #include "xbt/ex.h"
20 #include "xbt/dynar.h"
21 #include "xbt/dict.h"
22
23 // *****
24
25 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
26
27 XBT_EXPORT_NO_IMPORT(xbt_cfg_t) simgrid_config = NULL;
28
29 namespace {
30
31 static inline
32 void increment(e_xbt_cfgelm_type_t& type)
33 {
34   typedef std::underlying_type<e_xbt_cfgelm_type_t>::type underlying_type;
35   type = (e_xbt_cfgelm_type_t) ((underlying_type) type + 1);
36 }
37
38 }
39
40 namespace simgrid {
41 namespace config {
42
43 // A configuration variable:
44 struct ConfigurationElement {
45   /* Description */
46   std::string desc;
47
48   /* Allowed type of the variable */
49   e_xbt_cfgelm_type_t type;
50   bool isdefault = true;
51
52   /* Callback */
53   xbt_cfg_cb_t cb_set = nullptr;
54
55   /* Advanced callback (for xbt_cfgelm_string only) */
56   std::function<void(const char* value)> callback;
57
58   /* actual content (could be an union or something) */
59   xbt_dynar_t content = nullptr;
60
61   ~ConfigurationElement()
62   {
63     XBT_DEBUG("Frees cfgelm %p", this);
64     if (this->type != xbt_cfgelm_alias)
65       xbt_dynar_free(&(this->content));
66   }
67
68 };
69
70 struct Config {
71   xbt_dict_t options;
72
73   Config();
74   ~Config();
75
76   // No copy:
77   Config(Config const&) = delete;
78   Config& operator=(Config const&) = delete;
79 };
80
81 /* Internal stuff used in cache to free a variable */
82 static void xbt_cfgelm_free(void *data)
83 {
84   if (data)
85     delete (simgrid::config::ConfigurationElement*) data;
86 }
87
88 Config::Config() :
89   options(xbt_dict_new_homogeneous(xbt_cfgelm_free))
90 {}
91
92 Config::~Config()
93 {
94   XBT_DEBUG("Frees cfg set %p", this);
95   xbt_dict_free(&this->options);
96 }
97
98 }
99 }
100
101 static const char *xbt_cfgelm_type_name[xbt_cfgelm_type_count] = { "int", "double", "string", "boolean", "any", "outofbound" };
102
103 const struct xbt_boolean_couple xbt_cfgelm_boolean_values[] = {
104   { "yes",    "no"},
105   {  "on",   "off"},
106   {"true", "false"},
107   {   "1",     "0"},
108   {  NULL,    NULL}
109 };
110
111 /* Retrieve the variable we'll modify */
112 static simgrid::config::ConfigurationElement* xbt_cfgelm_get(xbt_cfg_t cfg, const char *name, e_xbt_cfgelm_type_t type);
113
114 /*----[ Memory management ]-----------------------------------------------*/
115 /** @brief Constructor
116  *
117  * Initialise a config set
118  */
119 xbt_cfg_t xbt_cfg_new(void)
120 {
121   return new simgrid::config::Config();
122 }
123
124 /** @brief Destructor */
125 void xbt_cfg_free(xbt_cfg_t * cfg)
126 {
127   delete *cfg;
128 }
129
130 /** @brief Dump a config set for debuging purpose
131  *
132  * @param name The name to give to this config set
133  * @param indent what to write at the beginning of each line (right number of spaces)
134  * @param cfg the config set
135  */
136 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
137 {
138   xbt_dict_t dict = cfg->options;
139   xbt_dict_cursor_t cursor = NULL;
140   simgrid::config::ConfigurationElement* variable = NULL;
141   char *key = NULL;
142   int i;
143   int size;
144   int ival;
145   char *sval;
146   double dval;
147
148   if (name)
149     printf("%s>> Dumping of the config set '%s':\n", indent, name);
150
151   xbt_dict_foreach(dict, cursor, key, variable) {
152     printf("%s  %s:", indent, key);
153
154     size = xbt_dynar_length(variable->content);
155     printf ("%s. Actual size=%d. postset=%p\n",
156             xbt_cfgelm_type_name[variable->type], size, variable->cb_set);
157
158     switch (variable->type) {
159     case xbt_cfgelm_int:
160       for (i = 0; i < size; i++) {
161         ival = xbt_dynar_get_as(variable->content, i, int);
162         printf("%s    %d\n", indent, ival);
163       }
164       break;
165     case xbt_cfgelm_double:
166       for (i = 0; i < size; i++) {
167         dval = xbt_dynar_get_as(variable->content, i, double);
168         printf("%s    %f\n", indent, dval);
169       }
170       break;
171     case xbt_cfgelm_string:
172       for (i = 0; i < size; i++) {
173         sval = xbt_dynar_get_as(variable->content, i, char *);
174         printf("%s    %s\n", indent, sval);
175       }
176       break;
177     case xbt_cfgelm_boolean:
178       for (i = 0; i < size; i++) {
179         ival = xbt_dynar_get_as(variable->content, i, int);
180         printf("%s    %d\n", indent, ival);
181       }
182       break;
183     case xbt_cfgelm_alias:
184       /* no content */
185       break;
186     default:
187       printf("%s    Invalid type!!\n", indent);
188       break;
189     }
190   }
191
192   if (name)
193     printf("%s<< End of the config set '%s'\n", indent, name);
194   fflush(stdout);
195
196   xbt_dict_cursor_free(&cursor);
197 }
198
199 /*----[ Registering stuff ]-----------------------------------------------*/
200 /** @brief Register an element within a config set
201  *
202  *  @param cfg the config set
203  *  @param name the name of the config element
204  *  @param desc a description for this item (used by xbt_cfg_help())
205  *  @param type the type of the config element
206  *  @param cb_set callback function called when a value is set
207  */
208 static void xbt_cfg_register(
209   xbt_cfg_t * cfg, const char *name, const char *desc, e_xbt_cfgelm_type_t type,
210   xbt_cfg_cb_t cb_set,
211   std::function<void(const char* value)> callback = std::function<void(const char* value)>())
212 {
213   if (*cfg == NULL)
214     *cfg = xbt_cfg_new();
215   xbt_assert(type >= xbt_cfgelm_int && type <= xbt_cfgelm_boolean,
216               "type of %s not valid (%d should be between %d and %d)",
217              name, (int)type, xbt_cfgelm_int, xbt_cfgelm_boolean);
218
219   simgrid::config::ConfigurationElement* res = (simgrid::config::ConfigurationElement*) xbt_dict_get_or_null((*cfg)->options, name);
220   xbt_assert(NULL == res, "Refusing to register the config element '%s' twice.", name);
221
222   res = new simgrid::config::ConfigurationElement();
223   XBT_DEBUG("Register cfg elm %s (%s) (%s (=%d) @%p in set %p)",
224             name, desc, xbt_cfgelm_type_name[type], (int)type, res, *cfg);
225   res->type = type;
226   if (desc)
227     res->desc = desc;
228   res->cb_set = cb_set;
229   res->callback = std::move(callback);
230
231   switch (type) {
232   case xbt_cfgelm_int:
233     res->content = xbt_dynar_new(sizeof(int), NULL);
234     break;
235   case xbt_cfgelm_double:
236     res->content = xbt_dynar_new(sizeof(double), NULL);
237     break;
238   case xbt_cfgelm_string:
239     res->content = xbt_dynar_new(sizeof(char *), xbt_free_ref);
240     break;
241   case xbt_cfgelm_boolean:
242     res->content = xbt_dynar_new(sizeof(int), NULL);
243     break;
244   default:
245     XBT_ERROR("%d is an invalid type code", (int)type);
246     break;
247   }
248
249   xbt_dict_set((*cfg)->options, name, res, NULL);
250 }
251
252 void xbt_cfg_register_double(const char *name, double default_value,xbt_cfg_cb_t cb_set, const char *desc){
253   xbt_cfg_register(&simgrid_config,name,desc,xbt_cfgelm_double,cb_set);
254   xbt_cfg_setdefault_double(name, default_value);
255 }
256 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc) {
257   xbt_cfg_register(&simgrid_config,name,desc,xbt_cfgelm_int,cb_set);
258   xbt_cfg_setdefault_int(name, default_value);
259 }
260 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc){
261   xbt_cfg_register(&simgrid_config,name,desc,xbt_cfgelm_string,cb_set);
262   xbt_cfg_setdefault_string(name, default_value);
263 }
264 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc){
265   xbt_cfg_register(&simgrid_config,name,desc,xbt_cfgelm_boolean,cb_set);
266   xbt_cfg_setdefault_boolean(name, default_value);
267 }
268
269 void xbt_cfg_register_alias(const char *newname, const char *oldname)
270 {
271   if (simgrid_config == NULL)
272     simgrid_config = xbt_cfg_new();
273
274   simgrid::config::ConfigurationElement* res = (simgrid::config::ConfigurationElement*) xbt_dict_get_or_null(simgrid_config->options, oldname);
275   xbt_assert(NULL == res, "Refusing to register the option '%s' twice.", oldname);
276
277   res = (simgrid::config::ConfigurationElement*) xbt_dict_get_or_null(simgrid_config->options, newname);
278   xbt_assert(res, "Cannot define an alias to the non-existing option '%s'.", newname);
279
280   res = new simgrid::config::ConfigurationElement();
281   XBT_DEBUG("Register cfg alias %s -> %s)",oldname,newname);
282
283   res->desc = std::string("Deprecated alias for ")+std::string(newname);
284   res->type = xbt_cfgelm_alias;
285   res->content = (xbt_dynar_t)newname;
286
287   xbt_dict_set(simgrid_config->options, oldname, res, NULL);
288 }
289
290 /**
291  * @brief Parse a string and register the stuff described.
292  *
293  * @param cfg the config set
294  * @param entry a string describing the element to register
295  *
296  * The string may consist in several variable descriptions separated by a space.
297  * Each of them must use the following syntax: \<name\>:\<type\>
298  * with type being one of  'string','int','bool' or 'double'.
299  *
300  * Note that this does not allow to set the description, so you should prefer the other interface
301  */
302 void xbt_cfg_register_str(xbt_cfg_t * cfg, const char *entry)
303 {
304   char *entrycpy = xbt_strdup(entry);
305   char *tok;
306
307   e_xbt_cfgelm_type_t type;
308   XBT_DEBUG("Register string '%s'", entry);
309
310   tok = strchr(entrycpy, ':');
311   xbt_assert(tok, "Invalid config element descriptor: %s; Should be <name>:<type>", entry);
312   *(tok++) = '\0';
313
314   for (type = (e_xbt_cfgelm_type_t)0; type < xbt_cfgelm_type_count && strcmp(tok, xbt_cfgelm_type_name[type]); increment(type));
315   xbt_assert(type < xbt_cfgelm_type_count,
316       "Invalid type in config element descriptor: %s; Should be one of 'string', 'int' or 'double'.", entry);
317
318   xbt_cfg_register(cfg, entrycpy, NULL, type, NULL);
319
320   free(entrycpy);               /* strdup'ed by dict mechanism, but cannot be const */
321 }
322
323 /** @brief Displays the declared aliases and their description */
324 void xbt_cfg_aliases(void)
325 {
326   xbt_dict_cursor_t dict_cursor;
327   unsigned int dynar_cursor;
328   simgrid::config::ConfigurationElement* variable;
329   char *name;
330   xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
331
332   xbt_dict_foreach(simgrid_config->options, dict_cursor, name, variable)
333     xbt_dynar_push(names, &name);
334   xbt_dynar_sort_strings(names);
335
336   xbt_dynar_foreach(names, dynar_cursor, name) {
337     variable = (simgrid::config::ConfigurationElement*) xbt_dict_get(simgrid_config->options, name);
338
339     if (variable->type == xbt_cfgelm_alias)
340       printf("   %s: %s\n", name, variable->desc.c_str());
341   }
342 }
343
344 /** @brief Displays the declared options and their description */
345 void xbt_cfg_help(void)
346 {
347   xbt_dict_cursor_t dict_cursor;
348   unsigned int dynar_cursor;
349   simgrid::config::ConfigurationElement* variable;
350   char *name;
351   xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
352
353   xbt_dict_foreach(simgrid_config->options, dict_cursor, name, variable)
354     xbt_dynar_push(names, &name);
355   xbt_dynar_sort_strings(names);
356
357   xbt_dynar_foreach(names, dynar_cursor, name) {
358     int size;
359     variable = (simgrid::config::ConfigurationElement*) xbt_dict_get(simgrid_config->options, name);
360     if (variable->type == xbt_cfgelm_alias)
361       continue;
362
363     printf("   %s: %s\n", name, variable->desc.c_str());
364     printf("       Type: %s; ", xbt_cfgelm_type_name[variable->type]);
365     size = xbt_dynar_length(variable->content);
366     printf("Current value: ");
367
368     if (size != 1)
369       printf(size == 0 ? "n/a\n" : "{ ");
370     for (int i = 0; i < size; i++) {
371       const char *sep = (size == 1 ? "\n" : (i < size - 1 ? ", " : " }\n"));
372
373       switch (variable->type) {
374       case xbt_cfgelm_int:
375         printf("%d%s", xbt_dynar_get_as(variable->content, i, int), sep);
376         break;
377       case xbt_cfgelm_double:
378         printf("%f%s", xbt_dynar_get_as(variable->content, i, double), sep);
379         break;
380       case xbt_cfgelm_string:
381         printf("'%s'%s", xbt_dynar_get_as(variable->content, i, char *), sep);
382         break;
383       case xbt_cfgelm_boolean: {
384         int b = xbt_dynar_get_as(variable->content, i, int);
385         const char *bs = b ? xbt_cfgelm_boolean_values[0].true_val: xbt_cfgelm_boolean_values[0].false_val;
386         if (b == 0 || b == 1)
387           printf("'%s'%s", bs, sep);
388         else
389           printf("'%s/%d'%s", bs, b, sep);
390         break;
391       }
392       default:
393         printf("Invalid type!!%s", sep);
394         break;
395       }
396     }
397   }
398   xbt_dynar_free(&names);
399 }
400
401 static simgrid::config::ConfigurationElement* xbt_cfgelm_get(xbt_cfg_t cfg, const char *name, e_xbt_cfgelm_type_t type)
402 {
403   simgrid::config::ConfigurationElement* res = (simgrid::config::ConfigurationElement*) xbt_dict_get_or_null(cfg->options, name);
404
405   // The user used the old name. Switch to the new one after a short warning
406   while (res && res->type == xbt_cfgelm_alias) {
407     const char* newname = (const char *)res->content;
408     XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, newname);
409     res = xbt_cfgelm_get(cfg, newname, type);
410   }
411
412   if (!res) {
413     xbt_cfg_help();
414     fflush(stdout);
415     THROWF(not_found_error, 0, "No registered variable '%s' in this config set.", name);
416   }
417
418   xbt_assert(type == xbt_cfgelm_any || res->type == type,
419               "You tried to access to the config element %s as an %s, but its type is %s.",
420               name, xbt_cfgelm_type_name[type], xbt_cfgelm_type_name[res->type]);
421   return res;
422 }
423
424 /** @brief Get the type of this variable in that configuration set
425  *
426  * @param cfg the config set
427  * @param name the name of the element
428  *
429  * @return the type of the given element
430  */
431 e_xbt_cfgelm_type_t xbt_cfg_get_type(xbt_cfg_t cfg, const char *name)
432 {
433   simgrid::config::ConfigurationElement* variable = NULL;
434
435   variable = (simgrid::config::ConfigurationElement*) xbt_dict_get_or_null(cfg->options, name);
436   if (!variable)
437     THROWF(not_found_error, 0, "Can't get the type of '%s' since this variable does not exist", name);
438
439   XBT_DEBUG("type in variable = %d", (int)variable->type);
440   return variable->type;
441 }
442
443 /*----[ Setting ]---------------------------------------------------------*/
444 /**  @brief va_args version of xbt_cfg_set
445  *
446  * @param cfg config set to fill
447  * @param name  variable name
448  * @param pa  variable value
449  *
450  * Add some values to the config set.
451  */
452 void xbt_cfg_set_vargs(xbt_cfg_t cfg, const char *name, va_list pa)
453 {
454   char *str;
455   int i;
456   double d;
457   e_xbt_cfgelm_type_t type = xbt_cfgelm_type_count; /* Set a dummy value to make gcc happy. It cannot get uninitialized */
458
459   xbt_ex_t e;
460
461   TRY {
462     type = xbt_cfg_get_type(cfg, name);
463   }
464   CATCH(e) {
465     if (e.category == not_found_error) {
466       xbt_ex_free(e);
467       THROWF(not_found_error, 0, "Can't set the property '%s' since it's not registered", name);
468     }
469     RETHROW;
470   }
471
472   switch (type) {
473   case xbt_cfgelm_string:
474     str = va_arg(pa, char *);
475     xbt_cfg_set_string(name, str);
476     break;
477   case xbt_cfgelm_int:
478     i = va_arg(pa, int);
479     xbt_cfg_set_int(name, i);
480     break;
481   case xbt_cfgelm_double:
482     d = va_arg(pa, double);
483     xbt_cfg_set_double(name, d);
484     break;
485   case xbt_cfgelm_boolean:
486     str = va_arg(pa, char *);
487     xbt_cfg_set_boolean(name, str);
488     break;
489   default:
490     xbt_die("Config element variable %s not valid (type=%d)", name, (int)type);
491   }
492 }
493
494 /** @brief Add a NULL-terminated list of pairs {(char*)key, value} to the set
495  *
496  * @param cfg config set to fill
497  * @param name variable name
498  * @param ... variable value
499  */
500 void xbt_cfg_set(xbt_cfg_t cfg, const char *name, ...)
501 {
502   va_list pa;
503
504   va_start(pa, name);
505   xbt_cfg_set_vargs(cfg, name, pa);
506   va_end(pa);
507 }
508
509 /** @brief Add values parsed from a string into a config set
510  *
511  * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
512  * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
513  * already registered variable, and [value] conforms to the data type under which this variable was registered.
514  *
515  * @todo This is a crude manual parser, it should be a proper lexer.
516  */
517 void xbt_cfg_set_parse(const char *options)
518 {
519   if (!options || !strlen(options)) {   /* nothing to do */
520     return;
521   }
522   char *optionlist_cpy = xbt_strdup(options);
523
524   XBT_DEBUG("List to parse and set:'%s'", options);
525   char *option = optionlist_cpy;
526   while (1) {                   /* breaks in the code */
527     if (!option)
528       break;
529     char *name = option;
530     int len = strlen(name);
531     XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
532
533     /* Pass the value */
534     while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
535       XBT_DEBUG("Take %c.", *option);
536       option++;
537     }
538     if (option - name == len) {
539       XBT_DEBUG("Boundary=EOL");
540       option = NULL;            /* don't do next iteration */
541     } else {
542       XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
543       /* Pass the following blank chars */
544       *(option++) = '\0';
545       while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
546         /*      fprintf(stderr,"Ignore a blank char.\n"); */
547         option++;
548       }
549       if (option - name == len - 1)
550         option = NULL;          /* don't do next iteration */
551     }
552     XBT_DEBUG("parse now:'%s'; parse later:'%s'", name, option);
553
554     if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
555       continue;
556     if (!strlen(name))
557       break;
558
559     char *val = strchr(name, ':');
560     xbt_assert(val, "Option '%s' badly formatted. Should be of the form 'name:value'", name);
561     /* don't free(optionlist_cpy) if the assert fails, 'name' points inside it */
562     *(val++) = '\0';
563
564     if (strncmp(name, "contexts/", strlen("contexts/")) && strncmp(name, "path", strlen("path")))
565       XBT_INFO("Configuration change: Set '%s' to '%s'", name, val);
566
567     TRY {
568       xbt_cfg_set_as_string(name,val);
569     } CATCH_ANONYMOUS {
570       free(optionlist_cpy);
571       RETHROW;
572     }
573   }
574   free(optionlist_cpy);
575 }
576
577 /** @brief Set the value of a variable, using the string representation of that value
578  *
579  * @param key name of the variable to modify
580  * @param value string representation of the value to set
581  *
582  * @return the first char after the parsed value in val
583  */
584
585 void *xbt_cfg_set_as_string(const char *key, const char *value) {
586   xbt_ex_t e;
587
588   char *ret;
589   volatile simgrid::config::ConfigurationElement* variable = NULL;
590   int i;
591   double d;
592
593   TRY {
594     while (variable == NULL) {
595       variable = (simgrid::config::ConfigurationElement*) xbt_dict_get(simgrid_config->options, key);
596       if (variable->type == xbt_cfgelm_alias) {
597         const char *newname = (const char*)variable->content;
598         XBT_INFO("Note: configuration '%s' is deprecated. Please use '%s' instead.", key, newname);
599         key = newname;
600         variable = NULL;
601       }
602     }
603   } CATCH(e) {
604     if (e.category == not_found_error) {
605       xbt_ex_free(e);
606       THROWF(not_found_error, 0, "No registered variable corresponding to '%s'.", key);
607     }
608     RETHROW;
609   }
610
611   switch (variable->type) {
612   case xbt_cfgelm_string:
613     xbt_cfg_set_string(key, value);     /* throws */
614     break;
615   case xbt_cfgelm_int:
616     i = strtol(value, &ret, 0);
617     if (ret == value) {
618       xbt_die("Value of option %s not valid. Should be an integer", key);
619     }
620     xbt_cfg_set_int(key, i);  /* throws */
621     break;
622   case xbt_cfgelm_double:
623     d = strtod(value, &ret);
624     if (ret == value) {
625       xbt_die("Value of option %s not valid. Should be a double", key);
626     }
627     xbt_cfg_set_double(key, d);       /* throws */
628     break;
629   case xbt_cfgelm_boolean:
630     xbt_cfg_set_boolean(key, value);  /* throws */
631     ret = (char *)value + strlen(value);
632     break;
633   default:
634     THROWF(unknown_error, 0, "Type of config element %s is not valid.", key);
635     break;
636   }
637   return ret;
638 }
639
640 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
641  *
642  * This is useful to change the default value of a variable while allowing
643  * users to override it with command line arguments
644  */
645 void xbt_cfg_setdefault_int(const char *name, int val)
646 {
647   simgrid::config::ConfigurationElement* variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_int);
648
649   if (variable->isdefault){
650     xbt_cfg_set_int(name, val);
651     variable->isdefault = true;
652   } else
653     XBT_DEBUG("Do not override configuration variable '%s' with value '%d' because it was already set.", name, val);
654 }
655
656 /** @brief Set an integer 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_double(const char *name, double val)
662 {
663   simgrid::config::ConfigurationElement* variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_double);
664
665   if (variable->isdefault) {
666     xbt_cfg_set_double(name, val);
667     variable->isdefault = true;
668   } else
669     XBT_DEBUG("Do not override configuration variable '%s' with value '%f' because it was already set.", name, val);
670 }
671
672 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
673  *
674  * This is useful to change the default value of a variable while allowing
675  * users to override it with command line arguments
676  */
677 void xbt_cfg_setdefault_string(const char *name, const char *val)
678 {
679   simgrid::config::ConfigurationElement* variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_string);
680
681   if (variable->isdefault){
682     xbt_cfg_set_string(name, val);
683     variable->isdefault = true;
684   } else
685     XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.", name, val);
686 }
687
688 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
689  *
690  * This is useful to change the default value of a variable while allowing
691  * users to override it with command line arguments
692  */
693 void xbt_cfg_setdefault_boolean(const char *name, const char *val)
694 {
695   simgrid::config::ConfigurationElement* variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_boolean);
696
697   if (variable->isdefault){
698     xbt_cfg_set_boolean(name, val);
699     variable->isdefault = true;
700   }
701    else
702     XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.", name, val);
703 }
704
705 /** @brief Set an integer value to \a name within \a cfg
706  *
707  * @param name the name of the variable
708  * @param val the value of the variable
709  */
710 void xbt_cfg_set_int(const char *name, int val)
711 {
712   simgrid::config::ConfigurationElement* variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_int);
713
714   xbt_dynar_set(variable->content, 0, &val);
715
716   if (variable->cb_set)
717     variable->cb_set(name);
718   variable->isdefault = false;
719 }
720
721 /** @brief Set or add a double value to \a name within \a cfg
722  *
723  * @param name the name of the variable
724  * @param val the double to set
725  */
726 void xbt_cfg_set_double(const char *name, double val)
727 {
728   simgrid::config::ConfigurationElement* variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_double);
729
730   xbt_dynar_set(variable->content, 0, &val);
731
732   if (variable->cb_set)
733     variable->cb_set(name);
734   variable->isdefault = false;
735 }
736
737 /** @brief Set or add a string value to \a name within \a cfg
738  *
739  * @param cfg the config set
740  * @param name the name of the variable
741  * @param val the value to be added
742  *
743  */
744 void xbt_cfg_set_string(const char *name, const char *val)
745 {
746   char *newval = xbt_strdup(val);
747   simgrid::config::ConfigurationElement* variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_string);
748
749   if (!xbt_dynar_is_empty(variable->content)) {
750     char *sval = xbt_dynar_get_as(variable->content, 0, char *);
751     free(sval);
752   }
753
754   xbt_dynar_set(variable->content, 0, &newval);
755
756   if (variable->cb_set)
757     variable->cb_set(name);
758
759   if (variable->callback) {
760     try {
761       variable->callback(val);
762     }
763     catch(std::range_error& e) {
764       xbt_die("Invalid flag %s=%s: %s", val, name, e.what());
765     }
766     catch(std::exception& e) {
767       xbt_die("Error for flag %s=%s: %s", val, name, e.what());
768     }
769     catch(...) {
770       xbt_die("Error for flag %s=%s", val, name);
771     }
772   }
773
774   variable->isdefault = false;
775 }
776
777 /** @brief Set or add a boolean value to \a name within \a cfg
778  *
779  * @param name the name of the variable
780  * @param val the value of the variable
781  */
782 void xbt_cfg_set_boolean(const char *name, const char *val)
783 {
784   int bval=-1;
785   simgrid::config::ConfigurationElement* variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_boolean);
786
787   for (int i = 0; xbt_cfgelm_boolean_values[i].true_val != NULL; i++) {
788     if (strcmp(val, xbt_cfgelm_boolean_values[i].true_val) == 0){
789       bval = 1;
790       break;
791     }
792     if (strcmp(val, xbt_cfgelm_boolean_values[i].false_val) == 0){
793       bval = 0;
794       break;
795     }
796   }
797   xbt_assert(bval != -1, "Value of option '%s' not valid. Should be a boolean (yes,no,on,off,true,false,0,1)", val);
798   xbt_dynar_set(variable->content, 0, &bval);
799
800   if (variable->cb_set)
801     variable->cb_set(name);
802   variable->isdefault = false;
803 }
804
805
806 /* Say if the value is the default value */
807 int xbt_cfg_is_default_value(const char *name)
808 {
809   simgrid::config::ConfigurationElement* variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_any);
810   return variable->isdefault;
811 }
812
813 /*----[ Getting ]---------------------------------------------------------*/
814 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
815  *
816  * @param name the name of the variable
817  *
818  * Returns the first value from the config set under the given name.
819  * If there is more than one value, it will issue a warning. Consider using xbt_cfg_get_dynar() instead.
820  */
821 int xbt_cfg_get_int(const char *name)
822 {
823   simgrid::config::ConfigurationElement* variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_int);
824
825   if (xbt_dynar_length(variable->content) > 1) {
826     XBT_WARN("You asked for the first value of the config element '%s', but there is %lu values",
827          name, xbt_dynar_length(variable->content));
828   }
829
830   return xbt_dynar_get_as(variable->content, 0, int);
831 }
832
833 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
834  *
835  * @param cfg the config set
836  * @param name the name of the variable
837  *
838  * Returns the first value from the config set under the given name.
839  * If there is more than one value, it will issue a warning. Consider using xbt_cfg_get_dynar() instead.
840  */
841 double xbt_cfg_get_double(const char *name)
842 {
843   simgrid::config::ConfigurationElement* variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_double);
844
845   if (xbt_dynar_length(variable->content) > 1) {
846     XBT_WARN ("You asked for the first value of the config element '%s', but there is %lu values\n",
847          name, xbt_dynar_length(variable->content));
848   }
849
850   return xbt_dynar_get_as(variable->content, 0, double);
851 }
852
853 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
854  *
855  * @param cfg the config set
856  * @param name the name of the variable
857  *
858  * Returns the first value from the config set under the given name.
859  * If there is more than one value, it will issue a warning. Consider using
860  * xbt_cfg_get_dynar() instead. Returns NULL if there is no value.
861  *
862  * \warning the returned value is the actual content of the config set
863  */
864 char *xbt_cfg_get_string(const char *name)
865 {
866   simgrid::config::ConfigurationElement* variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_string);
867
868   if (xbt_dynar_length(variable->content) > 1) {
869     XBT_WARN("You asked for the first value of the config element '%s', but there is %lu values\n",
870          name, xbt_dynar_length(variable->content));
871   } else if (xbt_dynar_is_empty(variable->content)) {
872     return NULL;
873   }
874
875   return xbt_dynar_get_as(variable->content, 0, char *);
876 }
877
878 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
879  *
880  * @param cfg the config set
881  * @param name the name of the variable
882  *
883  * Returns the first value from the config set under the given name.
884  * If there is more than one value, it will issue a warning. Consider using xbt_cfg_get_dynar() instead.
885  */
886 int xbt_cfg_get_boolean(const char *name)
887 {
888   simgrid::config::ConfigurationElement* variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_boolean);
889
890   if (xbt_dynar_length(variable->content) > 1) {
891     XBT_WARN("You asked for the first value of the config element '%s', but there is %lu values",
892          name, xbt_dynar_length(variable->content));
893   }
894
895   return xbt_dynar_get_as(variable->content, 0, int);
896 }
897
898 namespace simgrid {
899 namespace config {
900
901 bool parseBool(const char* value)
902 {
903   for (int i = 0; xbt_cfgelm_boolean_values[i].true_val != NULL; i++) {
904     if (std::strcmp(value, xbt_cfgelm_boolean_values[i].true_val) == 0)
905       return true;
906     if (std::strcmp(value, xbt_cfgelm_boolean_values[i].false_val) == 0)
907       return false;
908   }
909   throw std::range_error("not a boolean");
910 }
911
912 double parseDouble(const char* value)
913 {
914   char* end;
915   errno = 0;
916   double res = std::strtod(value, &end);
917   if (errno == ERANGE)
918     throw std::range_error("out of range");
919   else if (errno)
920     xbt_die("Unexpected errno");
921   if (end == value || *end != '\0')
922     throw std::range_error("invalid double");
923   else
924     return res;
925 }
926
927 long int parseLong(const char* value)
928 {
929   char* end;
930   errno = 0;
931   long int res = std::strtol(value, &end, 0);
932   if (errno) {
933     if (res == LONG_MIN && errno == ERANGE)
934       throw std::range_error("underflow");
935     else if (res == LONG_MAX && errno == ERANGE)
936       throw std::range_error("overflow");
937     xbt_die("Unexpected errno");
938   }
939   if (end == value || *end != '\0')
940     throw std::range_error("invalid integer");
941   else
942     return res;
943 }
944
945 void declareFlag(const char* name, const char* description,
946   std::function<void(const char* value)> callback)
947 {
948   xbt_cfg_register(&simgrid_config, name, description, xbt_cfgelm_string, NULL,
949     std::move(callback));
950 }
951
952 }
953 }
954
955 #ifdef SIMGRID_TEST
956
957 #include <string>
958
959 #include "xbt.h"
960 #include "xbt/ex.h"
961
962 #include <xbt/config.hpp>
963
964 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
965
966 XBT_TEST_SUITE("config", "Configuration support");
967
968 static xbt_cfg_t make_set()
969 {
970   xbt_cfg_t set = NULL;
971
972   xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
973   xbt_cfg_register_str(&set, "speed:int");
974   xbt_cfg_register_str(&set, "peername:string");
975   xbt_cfg_register_str(&set, "user:string");
976
977   return set;
978 }                               /* end_of_make_set */
979
980 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
981
982 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
983 {
984   simgrid_config = make_set();
985   xbt_test_add("Alloc and free a config set");
986   xbt_cfg_set_parse("peername:veloce user:bidule");
987   xbt_cfg_free(&simgrid_config);
988 }
989
990 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
991 {
992   simgrid_config = make_set();
993   xbt_test_add("Get a single value");
994   {
995     /* get_single_value */
996     int ival;
997
998     xbt_cfg_set_parse("peername:toto:42 speed:42");
999     ival = xbt_cfg_get_int("speed");
1000     if (ival != 42)
1001       xbt_test_fail("Speed value = %d, I expected 42", ival);
1002   }
1003
1004   xbt_test_add("Access to a non-existant entry");
1005   {
1006     xbt_ex_t e;
1007
1008     TRY {
1009       xbt_cfg_set_parse("color:blue");
1010     } CATCH(e) {
1011       if (e.category != not_found_error)
1012         xbt_test_exception(e);
1013       xbt_ex_free(e);
1014     }
1015   }
1016   xbt_cfg_free(&simgrid_config);
1017 }
1018
1019 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
1020 {
1021   simgrid_config = make_set();
1022   xbt_test_add("C++ declaration of flags");
1023
1024   simgrid::config::Flag<int> int_flag("int", "", 0);
1025   simgrid::config::Flag<std::string> string_flag("string", "", "foo");
1026   simgrid::config::Flag<double> double_flag("double", "", 0.32);
1027   simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
1028   simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
1029
1030   xbt_test_add("Parse values");
1031   xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
1032   xbt_test_assert(int_flag == 42, "Check int flag");
1033   xbt_test_assert(string_flag == "bar", "Check string flag");
1034   xbt_test_assert(double_flag == 8.0, "Check double flag");
1035   xbt_test_assert(bool_flag1, "Check bool1 flag");
1036   xbt_test_assert(!bool_flag2, "Check bool2 flag");
1037
1038   xbt_cfg_free(&simgrid_config);
1039 }
1040
1041 #endif                          /* SIMGRID_TEST */