Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
7c8619f8a353e29b032ac2a50560746bf8b999e3
[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 <functional>
7 #include <string>
8 #include <type_traits>
9
10 #include <xbt/config.h>
11 #include <xbt/config.hpp>
12 #include "xbt/misc.h"
13 #include "xbt/sysdep.h"
14 #include "xbt/log.h"
15 #include "xbt/ex.h"
16 #include "xbt/dynar.h"
17 #include "xbt/dict.h"
18
19 // *****
20
21 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
22
23 XBT_EXPORT_NO_IMPORT(xbt_cfg_t) simgrid_config = NULL;
24
25 namespace {
26
27 // We could define some range/iterator for the num values.
28 static inline
29 void increment(e_xbt_cfgelm_type_t& type)
30 {
31   typedef std::underlying_type<e_xbt_cfgelm_type_t>::type underlying_type;
32   type = (e_xbt_cfgelm_type_t) ((underlying_type) type + 1);
33 }
34
35 }
36
37 /* xbt_cfgelm_t: the typedef corresponding to a config variable. */
38
39 typedef struct {
40   /* Description */
41   char *desc;
42
43   /* Allowed type of the variable */
44   e_xbt_cfgelm_type_t type;
45   unsigned isdefault:1;
46
47   /* Callbacks */
48   xbt_cfg_cb_t cb_set;
49
50   /* Advanced callbacks */
51   xbt_cfg_cb_ext_t cb_set_ext;
52   void* cb_set_data;
53   xbt_cfg_cb_free_t cb_set_free;
54
55   /* actual content (could be an union or something) */
56   xbt_dynar_t content;
57 } s_xbt_cfgelm_t, *xbt_cfgelm_t;
58
59 static const char *xbt_cfgelm_type_name[xbt_cfgelm_type_count] = { "int", "double", "string", "boolean", "any", "outofbound" };
60
61 const struct xbt_boolean_couple xbt_cfgelm_boolean_values[] = {
62   { "yes",    "no"},
63   {  "on",   "off"},
64   {"true", "false"},
65   {   "1",     "0"},
66   {  NULL,    NULL}
67 };
68
69 /* Internal stuff used in cache to free a variable */
70 static void xbt_cfgelm_free(void *data);
71
72 /* Retrieve the variable we'll modify */
73 static xbt_cfgelm_t xbt_cfgelm_get(xbt_cfg_t cfg, const char *name, e_xbt_cfgelm_type_t type);
74
75 /*----[ Memory management ]-----------------------------------------------*/
76 /** @brief Constructor
77  *
78  * Initialise a config set
79  */
80 xbt_cfg_t xbt_cfg_new(void)
81 {
82   return (xbt_cfg_t) xbt_dict_new_homogeneous(&xbt_cfgelm_free);
83 }
84
85 /** @brief Destructor */
86 void xbt_cfg_free(xbt_cfg_t * cfg)
87 {
88   XBT_DEBUG("Frees cfg set %p", cfg);
89   xbt_dict_free((xbt_dict_t *) cfg);
90 }
91
92 /** @brief Dump a config set for debuging purpose
93  *
94  * @param name The name to give to this config set
95  * @param indent what to write at the beginning of each line (right number of spaces)
96  * @param cfg the config set
97  */
98 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
99 {
100   xbt_dict_t dict = (xbt_dict_t) cfg;
101   xbt_dict_cursor_t cursor = NULL;
102   xbt_cfgelm_t variable = NULL;
103   char *key = NULL;
104   int i;
105   int size;
106   int ival;
107   char *sval;
108   double dval;
109
110   if (name)
111     printf("%s>> Dumping of the config set '%s':\n", indent, name);
112
113   xbt_dict_foreach(dict, cursor, key, variable) {
114     printf("%s  %s:", indent, key);
115
116     size = xbt_dynar_length(variable->content);
117     printf ("%s. Actual size=%d. postset=%p\n",
118             xbt_cfgelm_type_name[variable->type], size, variable->cb_set);
119
120     switch (variable->type) {
121     case xbt_cfgelm_int:
122       for (i = 0; i < size; i++) {
123         ival = xbt_dynar_get_as(variable->content, i, int);
124         printf("%s    %d\n", indent, ival);
125       }
126       break;
127     case xbt_cfgelm_double:
128       for (i = 0; i < size; i++) {
129         dval = xbt_dynar_get_as(variable->content, i, double);
130         printf("%s    %f\n", indent, dval);
131       }
132       break;
133     case xbt_cfgelm_string:
134       for (i = 0; i < size; i++) {
135         sval = xbt_dynar_get_as(variable->content, i, char *);
136         printf("%s    %s\n", indent, sval);
137       }
138       break;
139     case xbt_cfgelm_boolean:
140       for (i = 0; i < size; i++) {
141         ival = xbt_dynar_get_as(variable->content, i, int);
142         printf("%s    %d\n", indent, ival);
143       }
144       break;
145     case xbt_cfgelm_alias:
146       /* no content */
147       break;
148     default:
149       printf("%s    Invalid type!!\n", indent);
150       break;
151     }
152   }
153
154   if (name)
155     printf("%s<< End of the config set '%s'\n", indent, name);
156   fflush(stdout);
157
158   xbt_dict_cursor_free(&cursor);
159 }
160
161 /*
162  * free an config element
163  */
164 void xbt_cfgelm_free(void *data)
165 {
166   xbt_cfgelm_t c = (xbt_cfgelm_t) data;
167
168   XBT_DEBUG("Frees cfgelm %p", c);
169   if (!c)
170     return;
171   if (c->cb_set_free)
172     c->cb_set_free(c->cb_set_data);
173   xbt_free(c->desc);
174   if (c->type != xbt_cfgelm_alias)
175     xbt_dynar_free(&(c->content));
176   free(c);
177 }
178
179 /*----[ Registering stuff ]-----------------------------------------------*/
180 /** @brief Register an element within a config set
181  *
182  *  @param cfg the config set
183  *  @param name the name of the config element
184  *  @param desc a description for this item (used by xbt_cfg_help())
185  *  @param type the type of the config element
186  *  @param cb_set callback function called when a value is set
187  */
188 static void xbt_cfg_register(
189   xbt_cfg_t * cfg, const char *name, const char *desc, e_xbt_cfgelm_type_t type,
190   xbt_cfg_cb_t cb_set,
191   xbt_cfg_cb_ext_t cb_set_ext, void* cb_set_data, xbt_cfg_cb_free_t cb_set_free)
192 {
193   if (*cfg == NULL)
194     *cfg = xbt_cfg_new();
195   xbt_assert(type >= xbt_cfgelm_int && type <= xbt_cfgelm_boolean,
196               "type of %s not valid (%d should be between %d and %d)",
197              name, (int)type, xbt_cfgelm_int, xbt_cfgelm_boolean);
198
199   xbt_cfgelm_t res = (xbt_cfgelm_t) xbt_dict_get_or_null((xbt_dict_t) * cfg, name);
200   xbt_assert(NULL == res, "Refusing to register the config element '%s' twice.", name);
201
202   res = xbt_new(s_xbt_cfgelm_t, 1);
203   XBT_DEBUG("Register cfg elm %s (%s) (%s (=%d) @%p in set %p)",
204             name, desc, xbt_cfgelm_type_name[type], (int)type, res, *cfg);
205
206   res->desc = xbt_strdup(desc);
207   res->type = type;
208   res->cb_set = cb_set;
209   res->cb_set_ext = cb_set_ext;
210   res->cb_set_data = cb_set_data;
211   res->cb_set_free = cb_set_free;
212   res->isdefault = 1;
213
214   switch (type) {
215   case xbt_cfgelm_int:
216     res->content = xbt_dynar_new(sizeof(int), NULL);
217     break;
218   case xbt_cfgelm_double:
219     res->content = xbt_dynar_new(sizeof(double), NULL);
220     break;
221   case xbt_cfgelm_string:
222     res->content = xbt_dynar_new(sizeof(char *), xbt_free_ref);
223     break;
224   case xbt_cfgelm_boolean:
225     res->content = xbt_dynar_new(sizeof(int), NULL);
226     break;
227   default:
228     XBT_ERROR("%d is an invalid type code", (int)type);
229     break;
230   }
231   xbt_dict_set((xbt_dict_t) * cfg, name, res, NULL);
232 }
233
234
235
236 void xbt_cfg_register_double(const char *name, double default_value,xbt_cfg_cb_t cb_set, const char *desc){
237   xbt_cfg_register(&simgrid_config,name,desc,xbt_cfgelm_double,cb_set, NULL, NULL, NULL);
238   xbt_cfg_setdefault_double(name, default_value);
239 }
240 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc) {
241   xbt_cfg_register(&simgrid_config,name,desc,xbt_cfgelm_int,cb_set, NULL, NULL, NULL);
242   xbt_cfg_setdefault_int(name, default_value);
243 }
244 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc){
245   xbt_cfg_register(&simgrid_config,name,desc,xbt_cfgelm_string,cb_set, NULL, NULL, NULL);
246   xbt_cfg_setdefault_string(name, default_value);
247 }
248 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc){
249   xbt_cfg_register(&simgrid_config,name,desc,xbt_cfgelm_boolean,cb_set, NULL, NULL, NULL);
250   xbt_cfg_setdefault_boolean(name, default_value);
251 }
252
253 /** Register a config with an extended callback
254  *
255  *  @param name      Name of the flag
256  *  @param desc      Description of the flag
257  *  @param type      Type of the flag
258  *  @param cb        Extended callback
259  *  @param data      Data associated with the callback
260  *  @param data_free Function used to free the callback data (or NULL)
261  */
262 void xbt_cfg_register_ext(const char *name, const char *desc, e_xbt_cfgelm_type_t type,
263   xbt_cfg_cb_ext_t cb, void* data, xbt_cfg_cb_free_t data_free)
264 {
265   xbt_cfg_register(&simgrid_config, name, desc, type, NULL, cb, data, data_free);
266 }
267
268 void xbt_cfg_register_alias(const char *newname, const char *oldname)
269 {
270   if (simgrid_config == NULL)
271     simgrid_config = xbt_cfg_new();
272
273   xbt_cfgelm_t res = (xbt_cfgelm_t) xbt_dict_get_or_null((xbt_dict_t) simgrid_config, oldname);
274   xbt_assert(NULL == res, "Refusing to register the option '%s' twice.", oldname);
275
276   res = (xbt_cfgelm_t) xbt_dict_get_or_null((xbt_dict_t) simgrid_config, newname);
277   xbt_assert(res, "Cannot define an alias to the non-existing option '%s'.", newname);
278
279   res = xbt_new0(s_xbt_cfgelm_t, 1);
280   XBT_DEBUG("Register cfg alias %s -> %s)",oldname,newname);
281
282   res->desc = bprintf("Deprecated alias for %s",newname);
283   res->type = xbt_cfgelm_alias;
284   res->isdefault = 1;
285   res->content = (xbt_dynar_t)newname;
286
287   xbt_dict_set((xbt_dict_t) simgrid_config, 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, NULL, NULL, 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   xbt_cfgelm_t variable;
329   char *name;
330   xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
331
332   xbt_dict_foreach((xbt_dict_t )simgrid_config, 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 = (xbt_cfgelm_t) xbt_dict_get((xbt_dict_t )simgrid_config, name);
338
339     if (variable->type == xbt_cfgelm_alias)
340       printf("   %s: %s\n", name, variable->desc);
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   xbt_cfgelm_t variable;
350   char *name;
351   xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
352
353   xbt_dict_foreach((xbt_dict_t )simgrid_config, 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 = (xbt_cfgelm_t) xbt_dict_get((xbt_dict_t )simgrid_config, name);
360     if (variable->type == xbt_cfgelm_alias)
361       continue;
362
363     printf("   %s: %s\n", name, variable->desc);
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 xbt_cfgelm_t xbt_cfgelm_get(xbt_cfg_t cfg, const char *name, e_xbt_cfgelm_type_t type)
402 {
403   xbt_cfgelm_t res = (xbt_cfgelm_t) xbt_dict_get_or_null((xbt_dict_t) cfg, 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   xbt_cfgelm_t variable = NULL;
434
435   variable = (xbt_cfgelm_t) xbt_dict_get_or_null((xbt_dict_t) cfg, 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 xbt_cfgelm_t variable = NULL;
590   int i;
591   double d;
592
593   TRY {
594     while (variable == NULL) {
595       variable = (xbt_cfgelm_t) xbt_dict_get((xbt_dict_t) simgrid_config, 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   xbt_cfgelm_t 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 = 1;
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   xbt_cfgelm_t 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 = 1;
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   xbt_cfgelm_t 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 = 1;
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   xbt_cfgelm_t 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 = 1;
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   xbt_cfgelm_t 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   if (variable->cb_set_ext)
719     variable->cb_set_ext(name, variable->cb_set_data);
720   variable->isdefault = 0;
721 }
722
723 /** @brief Set or add a double value to \a name within \a cfg
724  *
725  * @param name the name of the variable
726  * @param val the double to set
727  */
728 void xbt_cfg_set_double(const char *name, double val)
729 {
730   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_double);
731
732   xbt_dynar_set(variable->content, 0, &val);
733
734   if (variable->cb_set)
735     variable->cb_set(name);
736   if (variable->cb_set_ext)
737     variable->cb_set_ext(name, variable->cb_set_data);
738   variable->isdefault = 0;
739 }
740
741 /** @brief Set or add a string value to \a name within \a cfg
742  *
743  * @param cfg the config set
744  * @param name the name of the variable
745  * @param val the value to be added
746  *
747  */
748 void xbt_cfg_set_string(const char *name, const char *val)
749 {
750   char *newval = xbt_strdup(val);
751   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_string);
752
753   if (!xbt_dynar_is_empty(variable->content)) {
754     char *sval = xbt_dynar_get_as(variable->content, 0, char *);
755     free(sval);
756   }
757
758   xbt_dynar_set(variable->content, 0, &newval);
759
760   if (variable->cb_set)
761     variable->cb_set(name);
762   if (variable->cb_set_ext)
763     variable->cb_set_ext(name, variable->cb_set_data);
764   variable->isdefault = 0;
765 }
766
767 /** @brief Set or add a boolean value to \a name within \a cfg
768  *
769  * @param name the name of the variable
770  * @param val the value of the variable
771  */
772 void xbt_cfg_set_boolean(const char *name, const char *val)
773 {
774   int bval=-1;
775   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_boolean);
776
777   for (int i = 0; xbt_cfgelm_boolean_values[i].true_val != NULL; i++) {
778     if (strcmp(val, xbt_cfgelm_boolean_values[i].true_val) == 0){
779       bval = 1;
780       break;
781     }
782     if (strcmp(val, xbt_cfgelm_boolean_values[i].false_val) == 0){
783       bval = 0;
784       break;
785     }
786   }
787   xbt_assert(bval != -1, "Value of option '%s' not valid. Should be a boolean (yes,no,on,off,true,false,0,1)", val);
788   xbt_dynar_set(variable->content, 0, &bval);
789
790   if (variable->cb_set)
791     variable->cb_set(name);
792   if (variable->cb_set_ext)
793     variable->cb_set_ext(name, variable->cb_set_data);
794   variable->isdefault = 0;
795 }
796
797
798 /* Say if the value is the default value */
799 int xbt_cfg_is_default_value(const char *name)
800 {
801   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_any);
802   return variable->isdefault;
803 }
804
805 /*----[ Getting ]---------------------------------------------------------*/
806 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
807  *
808  * @param name 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. Consider using xbt_cfg_get_dynar() instead.
812  */
813 int xbt_cfg_get_int(const char *name)
814 {
815   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_int);
816
817   if (xbt_dynar_length(variable->content) > 1) {
818     XBT_WARN("You asked for the first value of the config element '%s', but there is %lu values",
819          name, xbt_dynar_length(variable->content));
820   }
821
822   return xbt_dynar_get_as(variable->content, 0, int);
823 }
824
825 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
826  *
827  * @param cfg the config set
828  * @param name the name of the variable
829  *
830  * Returns the first value from the config set under the given name.
831  * If there is more than one value, it will issue a warning. Consider using xbt_cfg_get_dynar() instead.
832  */
833 double xbt_cfg_get_double(const char *name)
834 {
835   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_double);
836
837   if (xbt_dynar_length(variable->content) > 1) {
838     XBT_WARN ("You asked for the first value of the config element '%s', but there is %lu values\n",
839          name, xbt_dynar_length(variable->content));
840   }
841
842   return xbt_dynar_get_as(variable->content, 0, double);
843 }
844
845 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
846  *
847  * @param cfg the config set
848  * @param name the name of the variable
849  *
850  * Returns the first value from the config set under the given name.
851  * If there is more than one value, it will issue a warning. Consider using
852  * xbt_cfg_get_dynar() instead. Returns NULL if there is no value.
853  *
854  * \warning the returned value is the actual content of the config set
855  */
856 char *xbt_cfg_get_string(const char *name)
857 {
858   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_string);
859
860   if (xbt_dynar_length(variable->content) > 1) {
861     XBT_WARN("You asked for the first value of the config element '%s', but there is %lu values\n",
862          name, xbt_dynar_length(variable->content));
863   } else if (xbt_dynar_is_empty(variable->content)) {
864     return NULL;
865   }
866
867   return xbt_dynar_get_as(variable->content, 0, char *);
868 }
869
870 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
871  *
872  * @param cfg the config set
873  * @param name the name of the variable
874  *
875  * Returns the first value from the config set under the given name.
876  * If there is more than one value, it will issue a warning. Consider using xbt_cfg_get_dynar() instead.
877  */
878 int xbt_cfg_get_boolean(const char *name)
879 {
880   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_boolean);
881
882   if (xbt_dynar_length(variable->content) > 1) {
883     XBT_WARN("You asked for the first value of the config element '%s', but there is %lu values",
884          name, xbt_dynar_length(variable->content));
885   }
886
887   return xbt_dynar_get_as(variable->content, 0, int);
888 }
889
890 namespace simgrid {
891 namespace config {
892
893 static void callCallback(const char* name, void* data)
894 {
895   (*(std::function<void(const char*)>*) data)(name);
896 }
897
898 static void freeCallback(void* data)
899 {
900   delete (std::function<void(const char*)>*) data;
901 }
902
903 void registerConfig(const char* name, const char* description,
904   e_xbt_cfgelm_type_t type,
905   std::function<void(const char*)> callback)
906 {
907   std::function<void(const char*)>* code
908     = new std::function<void(const char*)>(std::move(callback));
909   xbt_cfg_register_ext(name, description, type,
910     callCallback, code, freeCallback);
911 }
912
913 }
914 }
915
916 #ifdef SIMGRID_TEST
917 #include "xbt.h"
918 #include "xbt/ex.h"
919
920 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
921
922 XBT_TEST_SUITE("config", "Configuration support");
923
924 static xbt_cfg_t make_set()
925 {
926   xbt_cfg_t set = NULL;
927
928   xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
929   xbt_cfg_register_str(&set, "speed:int");
930   xbt_cfg_register_str(&set, "peername:string");
931   xbt_cfg_register_str(&set, "user:string");
932
933   return set;
934 }                               /* end_of_make_set */
935
936 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
937
938 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
939 {
940   simgrid_config = make_set();
941   xbt_test_add("Alloc and free a config set");
942   xbt_cfg_set_parse("peername:veloce user:bidule");
943   xbt_cfg_free(&simgrid_config);
944 }
945
946 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
947 {
948   simgrid_config = make_set();
949   xbt_test_add("Get a single value");
950   {
951     /* get_single_value */
952     int ival;
953
954     xbt_cfg_set_parse("peername:toto:42 speed:42");
955     ival = xbt_cfg_get_int("speed");
956     if (ival != 42)
957       xbt_test_fail("Speed value = %d, I expected 42", ival);
958   }
959
960   xbt_test_add("Access to a non-existant entry");
961   {
962     xbt_ex_t e;
963
964     TRY {
965       xbt_cfg_set_parse("color:blue");
966     } CATCH(e) {
967       if (e.category != not_found_error)
968         xbt_test_exception(e);
969       xbt_ex_free(e);
970     }
971   }
972   xbt_cfg_free(&simgrid_config);
973 }
974 #endif                          /* SIMGRID_TEST */