Logo AND Algorithmique Numérique Distribuée

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