Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use const& for std::string parameter (sonar, again).
[simgrid.git] / src / xbt / config.cpp
1 /* Copyright (c) 2004-2021. The SimGrid Team. All rights reserved.     */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include <cstdio>
7
8 #include <algorithm>
9 #include <cerrno>
10 #include <cstring>
11 #include <climits>
12
13 #include <functional>
14 #include <map>
15 #include <memory>
16 #include <stdexcept>
17 #include <string>
18 #include <string>
19 #include <type_traits>
20 #include <typeinfo>
21 #include <vector>
22
23 #include "simgrid/Exception.hpp"
24 #include "simgrid/sg_config.hpp"
25 #include "xbt/dynar.h"
26 #include "xbt/log.h"
27 #include "xbt/misc.h"
28 #include "xbt/sysdep.h"
29 #include <xbt/config.h>
30 #include <xbt/config.hpp>
31
32 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
33
34 XBT_EXPORT_NO_IMPORT xbt_cfg_t simgrid_config = nullptr;
35
36 namespace simgrid {
37 namespace config {
38
39 namespace {
40
41 bool parse_bool(const char* value)
42 {
43   for (const char* true_value : {"yes", "on", "true", "1"})
44     if (std::strcmp(true_value, value) == 0)
45       return true;
46   for (const char* false_value : {"no", "off", "false", "0"})
47     if (std::strcmp(false_value, value) == 0)
48       return false;
49   throw std::range_error("not a boolean");
50 }
51
52 double parse_double(const char* value)
53 {
54   char* end;
55   errno = 0;
56   double res = std::strtod(value, &end);
57   if (errno == ERANGE)
58     throw std::range_error("out of range");
59   else if (errno)
60     xbt_die("Unexpected errno");
61   if (end == value || *end != '\0')
62     throw std::range_error("invalid double");
63   else
64     return res;
65 }
66
67 long int parse_long(const char* value)
68 {
69   char* end;
70   errno = 0;
71   long int res = std::strtol(value, &end, 0);
72   if (errno) {
73     if (res == LONG_MIN && errno == ERANGE)
74       throw std::range_error("underflow");
75     else if (res == LONG_MAX && errno == ERANGE)
76       throw std::range_error("overflow");
77     xbt_die("Unexpected errno");
78   }
79   if (end == value || *end != '\0')
80     throw std::range_error("invalid integer");
81   else
82     return res;
83 }
84
85 // ***** ConfigType *****
86
87 /// A trait which define possible options types:
88 template <class T> class ConfigType;
89
90 template <> class ConfigType<int> {
91 public:
92   static constexpr const char* type_name = "int";
93   static inline int parse(const char* value)
94   {
95     long val = parse_long(value);
96     if (val < INT_MIN)
97       throw std::range_error("underflow");
98     if (val > INT_MAX)
99       throw std::range_error("overflow");
100     return static_cast<int>(val);
101   }
102 };
103 template <> class ConfigType<double> {
104 public:
105   static constexpr const char* type_name = "double";
106   static inline double parse(const char* value)
107   {
108     return parse_double(value);
109   }
110 };
111 template <> class ConfigType<std::string> {
112 public:
113   static constexpr const char* type_name = "string";
114   static inline std::string parse(const char* value)
115   {
116     return std::string(value);
117   }
118 };
119 template <> class ConfigType<bool> {
120 public:
121   static constexpr const char* type_name = "boolean";
122   static inline bool parse(const char* value)
123   {
124     return parse_bool(value);
125   }
126 };
127
128 // **** Forward declarations ****
129
130 class ConfigurationElement ;
131 template<class T> class TypedConfigurationElement;
132
133 // **** ConfigurationElement ****
134
135 class ConfigurationElement {
136 private:
137   std::string key;
138   std::string desc;
139   bool isdefault = true;
140
141 public:
142   ConfigurationElement(const std::string& key, const std::string& desc) : key(key), desc(desc) {}
143
144   virtual ~ConfigurationElement() = default;
145
146   virtual std::string get_string_value()           = 0;
147   virtual void set_string_value(const char* value) = 0;
148   virtual const char* get_type_name()              = 0;
149
150   template <class T> T const& get_value() const
151   {
152     return static_cast<const TypedConfigurationElement<T>&>(*this).get_value();
153   }
154   template <class T> void set_value(T value)
155   {
156     static_cast<TypedConfigurationElement<T>&>(*this).set_value(std::move(value));
157   }
158   template <class T> void set_default_value(T value)
159   {
160     static_cast<TypedConfigurationElement<T>&>(*this).set_default_value(std::move(value));
161   }
162   void unset_default() { isdefault = false; }
163   bool is_default() const { return isdefault; }
164
165   std::string const& get_description() const { return desc; }
166   std::string const& get_key() const { return key; }
167 };
168
169 // **** TypedConfigurationElement<T> ****
170
171 // TODO, could we use boost::any with some Type* reference?
172 template<class T>
173 class TypedConfigurationElement : public ConfigurationElement {
174 private:
175   T content;
176   std::function<void(T&)> callback;
177
178 public:
179   TypedConfigurationElement(const std::string& key, const std::string& desc, T value = T())
180       : ConfigurationElement(key, desc), content(std::move(value))
181   {}
182   TypedConfigurationElement(const std::string& key, const std::string& desc, T value, std::function<void(T&)> callback)
183       : ConfigurationElement(key, desc), content(std::move(value)), callback(std::move(callback))
184   {}
185
186   std::string get_string_value() override;
187   const char* get_type_name() override;
188   void set_string_value(const char* value) override;
189
190   void update()
191   {
192     if (this->callback)
193       this->callback(this->content);
194   }
195
196   T const& get_value() const { return content; }
197
198   void set_value(T value)
199   {
200     this->content = std::move(value);
201     this->update();
202     this->unset_default();
203   }
204
205   void set_default_value(T value)
206   {
207     if (this->is_default()) {
208       this->content = std::move(value);
209       this->update();
210     } else {
211       XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.",
212                 get_key().c_str(), get_string_value().c_str());
213     }
214   }
215 };
216
217 template <class T> std::string TypedConfigurationElement<T>::get_string_value() // override
218 {
219   return to_string(content);
220 }
221
222 template <> std::string TypedConfigurationElement<double>::get_string_value() // override
223 {
224   // don't want std::to_string which uses %f, and formats very small values as 0.000000
225   return xbt::string_printf("%g", content);
226 }
227
228 template <class T> void TypedConfigurationElement<T>::set_string_value(const char* value) // override
229 {
230   this->content = ConfigType<T>::parse(value);
231   this->unset_default();
232   this->update();
233 }
234
235 template <class T> const char* TypedConfigurationElement<T>::get_type_name() // override
236 {
237   return ConfigType<T>::type_name;
238 }
239
240 } // end of anonymous namespace
241
242 // **** Config ****
243
244 class Config {
245 private:
246   // name -> ConfigElement:
247   std::map<std::string, std::unique_ptr<ConfigurationElement>, std::less<>> options;
248   // alias -> ConfigElement from options:
249   std::map<std::string, ConfigurationElement*, std::less<>> aliases;
250   bool warn_for_aliases = true;
251
252 public:
253   Config();
254
255   // No copy:
256   Config(Config const&) = delete;
257   Config& operator=(Config const&) = delete;
258
259   ConfigurationElement& operator[](const std::string& name);
260   void alias(const std::string& realname, const std::string& aliasname);
261
262   template <class T, class... A> TypedConfigurationElement<T>* register_option(const std::string& name, A&&... a)
263   {
264     xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.",
265                name.c_str());
266     auto* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
267     XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name.c_str(), variable->get_description().c_str(),
268               variable->get_type_name(), variable, this);
269     options[name].reset(variable);
270     variable->update();
271     return variable;
272   }
273
274   // Debug:
275   void dump(const char* name, const char* indent) const;
276   void show_aliases() const;
277   void help() const;
278
279 protected:
280   ConfigurationElement* get_dict_element(const std::string& name);
281 };
282
283 Config::Config()
284 {
285   atexit(&sg_config_finalize);
286 }
287
288 inline ConfigurationElement* Config::get_dict_element(const std::string& name)
289 {
290   auto opt = options.find(name);
291   if (opt != options.end()) {
292     return opt->second.get();
293   } else {
294     auto als = aliases.find(name);
295     if (als != aliases.end()) {
296       ConfigurationElement* res = als->second;
297       if (warn_for_aliases)
298         XBT_INFO("Option %s has been renamed to %s. Consider switching.", name.c_str(), res->get_key().c_str());
299       return res;
300     } else {
301       std::string msg = "Bad config key: " + name + "\nExisting config keys:\n";
302       for (auto const& elm : options)
303         msg += "  " + elm.first + ": (" + elm.second->get_type_name() + ")" + elm.second->get_string_value() + "\n";
304       throw std::out_of_range(msg);
305     }
306   }
307 }
308
309 inline ConfigurationElement& Config::operator[](const std::string& name)
310 {
311   return *(get_dict_element(name));
312 }
313
314 void Config::alias(const std::string& realname, const std::string& aliasname)
315 {
316   xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname.c_str());
317   ConfigurationElement* element = this->get_dict_element(realname);
318   xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname.c_str());
319   this->aliases.insert({aliasname, element});
320 }
321
322 /** @brief Dump a config set for debugging purpose
323  *
324  * @param name The name to give to this config set
325  * @param indent what to write at the beginning of each line (right number of spaces)
326  */
327 void Config::dump(const char* name, const char* indent) const
328 {
329   if (name)
330     XBT_CVERB(xbt_help, "%s>> Dumping of the config set '%s':", indent, name);
331
332   for (auto const& elm : options)
333     XBT_CVERB(xbt_help, "%s  %s: ()%s) %s", indent, elm.first.c_str(), elm.second->get_type_name(),
334               elm.second->get_string_value().c_str());
335
336   if (name)
337     XBT_CVERB(xbt_help, "%s<< End of the config set '%s'", indent, name);
338 }
339
340 /** @brief Displays the declared aliases and their replacement */
341 void Config::show_aliases() const
342 {
343   for (auto const& elm : aliases)
344     XBT_HELP("   %-40s %s", elm.first.c_str(), elm.second->get_key().c_str());
345 }
346
347 /** @brief Displays the declared options and their description */
348 void Config::help() const
349 {
350   for (auto const& elm : options) {
351     simgrid::config::ConfigurationElement* variable = elm.second.get();
352     XBT_HELP("   %s: %s", elm.first.c_str(), variable->get_description().c_str());
353     XBT_HELP("       Type: %s; Current value: %s", variable->get_type_name(), variable->get_string_value().c_str());
354   }
355 }
356
357 // ***** set_default *****
358
359 template <class T> XBT_PUBLIC void set_default(const char* name, T value)
360 {
361   (*simgrid_config)[name].set_default_value<T>(std::move(value));
362 }
363
364 template XBT_PUBLIC void set_default<int>(const char* name, int value);
365 template XBT_PUBLIC void set_default<double>(const char* name, double value);
366 template XBT_PUBLIC void set_default<bool>(const char* name, bool value);
367 template XBT_PUBLIC void set_default<std::string>(const char* name, std::string value);
368
369 bool is_default(const char* name)
370 {
371   return (*simgrid_config)[name].is_default();
372 }
373
374 // ***** set_value *****
375
376 template <class T> XBT_PUBLIC void set_value(const char* name, T value)
377 {
378   (*simgrid_config)[name].set_value<T>(std::move(value));
379 }
380
381 template XBT_PUBLIC void set_value<int>(const char* name, int value);
382 template XBT_PUBLIC void set_value<double>(const char* name, double value);
383 template XBT_PUBLIC void set_value<bool>(const char* name, bool value);
384 template XBT_PUBLIC void set_value<std::string>(const char* name, std::string value);
385
386 void set_as_string(const char* name, const std::string& value)
387 {
388   (*simgrid_config)[name].set_string_value(value.c_str());
389 }
390
391 void set_parse(const std::string& opt)
392 {
393   std::string options(opt);
394   XBT_DEBUG("List to parse and set:'%s'", options.c_str());
395   while (not options.empty()) {
396     XBT_DEBUG("Still to parse and set: '%s'", options.c_str());
397
398     // skip separators
399     size_t pos = options.find_first_not_of(" \t\n,");
400     options.erase(0, pos);
401     // find option
402     pos              = options.find_first_of(" \t\n,");
403     std::string name = options.substr(0, pos);
404     options.erase(0, pos);
405     XBT_DEBUG("parse now:'%s'; parse later:'%s'", name.c_str(), options.c_str());
406
407     if (name.empty())
408       continue;
409
410     pos = name.find(':');
411     xbt_assert(pos != std::string::npos, "Option '%s' badly formatted. Should be of the form 'name:value'",
412                name.c_str());
413
414     std::string val = name.substr(pos + 1);
415     name.erase(pos);
416
417     const std::string path("path");
418     if (name.compare(0, path.length(), path) != 0)
419       XBT_INFO("Configuration change: Set '%s' to '%s'", name.c_str(), val.c_str());
420
421     set_as_string(name.c_str(), val);
422   }
423 }
424
425 // ***** get_value *****
426
427 template <class T> XBT_PUBLIC T const& get_value(const std::string& name)
428 {
429   return (*simgrid_config)[name].get_value<T>();
430 }
431
432 template XBT_PUBLIC int const& get_value<int>(const std::string& name);
433 template XBT_PUBLIC double const& get_value<double>(const std::string& name);
434 template XBT_PUBLIC bool const& get_value<bool>(const std::string& name);
435 template XBT_PUBLIC std::string const& get_value<std::string>(const std::string& name);
436
437 // ***** alias *****
438
439 void alias(const char* realname, std::initializer_list<const char*> aliases)
440 {
441   for (auto const& aliasname : aliases)
442     simgrid_config->alias(realname, aliasname);
443 }
444
445 // ***** declare_flag *****
446
447 template <class T>
448 XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, T value,
449                              std::function<void(const T&)> callback)
450 {
451   if (simgrid_config == nullptr)
452     simgrid_config = new simgrid::config::Config();
453   simgrid_config->register_option<T>(name, description, std::move(value), std::move(callback));
454 }
455
456 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, int value,
457                                       std::function<void(int const&)> callback);
458 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, double value,
459                                       std::function<void(double const&)> callback);
460 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, bool value,
461                                       std::function<void(bool const&)> callback);
462 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, std::string value,
463                                       std::function<void(std::string const&)> callback);
464
465 void finalize()
466 {
467   delete simgrid_config;
468   simgrid_config = nullptr;
469 }
470
471 void show_aliases()
472 {
473   simgrid_config->show_aliases();
474 }
475
476 void help()
477 {
478   simgrid_config->help();
479 }
480 }
481 }
482
483 /*----[ Setting ]---------------------------------------------------------*/
484
485 /** @brief Set an integer value to \a name within \a cfg
486  *
487  * @param key the name of the variable
488  * @param value the value of the variable
489  */
490 void sg_cfg_set_int(const char* key, int value)
491 {
492   (*simgrid_config)[key].set_value<int>(value);
493 }
494
495 /** @brief Set or add a double value to \a name within \a cfg
496  *
497  * @param key the name of the variable
498  * @param value the double to set
499  */
500 void sg_cfg_set_double(const char* key, double value)
501 {
502   (*simgrid_config)[key].set_value<double>(value);
503 }
504
505 /** @brief Set or add a string value to \a name within \a cfg
506  *
507  * @param key the name of the variable
508  * @param value the value to be added
509  *
510  */
511 void sg_cfg_set_string(const char* key, const char* value)
512 {
513   (*simgrid_config)[key].set_value<std::string>(value);
514 }
515
516 /** @brief Set or add a boolean value to \a name within \a cfg
517  *
518  * @param key the name of the variable
519  * @param value the value of the variable
520  */
521 void sg_cfg_set_boolean(const char* key, const char* value)
522 {
523   (*simgrid_config)[key].set_value<bool>(simgrid::config::parse_bool(value));
524 }
525
526 /*----[ Getting ]---------------------------------------------------------*/
527 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
528  *
529  * @param key the name of the variable
530  *
531  * Returns the first value from the config set under the given name.
532  */
533 int sg_cfg_get_int(const char* key)
534 {
535   return (*simgrid_config)[key].get_value<int>();
536 }
537
538 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
539  *
540  * @param key the name of the variable
541  *
542  * Returns the first value from the config set under the given name.
543  */
544 double sg_cfg_get_double(const char* key)
545 {
546   return (*simgrid_config)[key].get_value<double>();
547 }
548
549 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
550  *
551  * @param key the name of the variable
552  *
553  * Returns the first value from the config set under the given name.
554  * If there is more than one value, it will issue a warning.
555  */
556 int sg_cfg_get_boolean(const char* key)
557 {
558   return (*simgrid_config)[key].get_value<bool>() ? 1 : 0;
559 }