Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Remove redundant "staitc" in anonymous namespaces.
[simgrid.git] / src / xbt / config.cpp
1 /* Copyright (c) 2004-2020. 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   ~TypedConfigurationElement() override = default;
186
187   std::string get_string_value() override;
188   const char* get_type_name() override;
189   void set_string_value(const char* value) override;
190
191   void update()
192   {
193     if (this->callback)
194       this->callback(this->content);
195   }
196
197   T const& get_value() const { return content; }
198
199   void set_value(T value)
200   {
201     this->content = std::move(value);
202     this->update();
203     this->unset_default();
204   }
205
206   void set_default_value(T value)
207   {
208     if (this->is_default()) {
209       this->content = std::move(value);
210       this->update();
211     } else {
212       XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.",
213                 get_key().c_str(), get_string_value().c_str());
214     }
215   }
216 };
217
218 template <class T> std::string TypedConfigurationElement<T>::get_string_value() // override
219 {
220   return to_string(content);
221 }
222
223 template <> std::string TypedConfigurationElement<double>::get_string_value() // override
224 {
225   // don't want std::to_string which uses %f, and formats very small values as 0.000000
226   return xbt::string_printf("%g", content);
227 }
228
229 template <class T> void TypedConfigurationElement<T>::set_string_value(const char* value) // override
230 {
231   this->content = ConfigType<T>::parse(value);
232   this->unset_default();
233   this->update();
234 }
235
236 template <class T> const char* TypedConfigurationElement<T>::get_type_name() // override
237 {
238   return ConfigType<T>::type_name;
239 }
240
241 } // end of anonymous namespace
242
243 // **** Config ****
244
245 class Config {
246 private:
247   // name -> ConfigElement:
248   std::map<std::string, std::unique_ptr<ConfigurationElement>> options;
249   // alias -> ConfigElement from options:
250   std::map<std::string, ConfigurationElement*> aliases;
251   bool warn_for_aliases = true;
252
253 public:
254   Config();
255
256   // No copy:
257   Config(Config const&) = delete;
258   Config& operator=(Config const&) = delete;
259
260   ConfigurationElement& operator[](const std::string& name);
261   void alias(const std::string& realname, const std::string& aliasname);
262
263   template <class T, class... A> TypedConfigurationElement<T>* register_option(const std::string& name, A&&... a)
264   {
265     xbt_assert(options.find(name) == options.end(), "Refusing to register the config element '%s' twice.",
266                name.c_str());
267     auto* variable = new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
268     XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)", name.c_str(), variable->get_description().c_str(),
269               variable->get_type_name(), variable, this);
270     options[name].reset(variable);
271     variable->update();
272     return variable;
273   }
274
275   // Debug:
276   void dump(const char* name, const char* indent) const;
277   void show_aliases() const;
278   void help() const;
279
280 protected:
281   ConfigurationElement* get_dict_element(const std::string& name);
282 };
283
284 Config::Config()
285 {
286   atexit(&sg_config_finalize);
287 }
288
289 inline ConfigurationElement* Config::get_dict_element(const std::string& name)
290 {
291   auto opt = options.find(name);
292   if (opt != options.end()) {
293     return opt->second.get();
294   } else {
295     auto als = aliases.find(name);
296     if (als != aliases.end()) {
297       ConfigurationElement* res = als->second;
298       if (warn_for_aliases)
299         XBT_INFO("Option %s has been renamed to %s. Consider switching.", name.c_str(), res->get_key().c_str());
300       return res;
301     } else {
302       std::string msg = "Bad config key: " + name + "\nExisting config keys:\n";
303       for (auto const& elm : options)
304         msg += "  " + elm.first + ": (" + elm.second->get_type_name() + ")" + elm.second->get_string_value() + "\n";
305       throw std::out_of_range(msg);
306     }
307   }
308 }
309
310 inline ConfigurationElement& Config::operator[](const std::string& name)
311 {
312   return *(get_dict_element(name));
313 }
314
315 void Config::alias(const std::string& realname, const std::string& aliasname)
316 {
317   xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname.c_str());
318   ConfigurationElement* element = this->get_dict_element(realname);
319   xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname.c_str());
320   this->aliases.insert({aliasname, element});
321 }
322
323 /** @brief Dump a config set for debugging purpose
324  *
325  * @param name The name to give to this config set
326  * @param indent what to write at the beginning of each line (right number of spaces)
327  */
328 void Config::dump(const char* name, const char* indent) const
329 {
330   if (name)
331     XBT_CVERB(xbt_help, "%s>> Dumping of the config set '%s':", indent, name);
332
333   for (auto const& elm : options)
334     XBT_CVERB(xbt_help, "%s  %s: ()%s) %s", indent, elm.first.c_str(), elm.second->get_type_name(),
335               elm.second->get_string_value().c_str());
336
337   if (name)
338     XBT_CVERB(xbt_help, "%s<< End of the config set '%s'", indent, name);
339 }
340
341 /** @brief Displays the declared aliases and their replacement */
342 void Config::show_aliases() const
343 {
344   for (auto const& elm : aliases)
345     XBT_HELP("   %-40s %s", elm.first.c_str(), elm.second->get_key().c_str());
346 }
347
348 /** @brief Displays the declared options and their description */
349 void Config::help() const
350 {
351   for (auto const& elm : options) {
352     simgrid::config::ConfigurationElement* variable = elm.second.get();
353     XBT_HELP("   %s: %s", elm.first.c_str(), variable->get_description().c_str());
354     XBT_HELP("       Type: %s; Current value: %s", variable->get_type_name(), variable->get_string_value().c_str());
355   }
356 }
357
358 // ***** set_default *****
359
360 template <class T> XBT_PUBLIC void set_default(const char* name, T value)
361 {
362   (*simgrid_config)[name].set_default_value<T>(std::move(value));
363 }
364
365 template XBT_PUBLIC void set_default<int>(const char* name, int value);
366 template XBT_PUBLIC void set_default<double>(const char* name, double value);
367 template XBT_PUBLIC void set_default<bool>(const char* name, bool value);
368 template XBT_PUBLIC void set_default<std::string>(const char* name, std::string value);
369
370 bool is_default(const char* name)
371 {
372   return (*simgrid_config)[name].is_default();
373 }
374
375 // ***** set_value *****
376
377 template <class T> XBT_PUBLIC void set_value(const char* name, T value)
378 {
379   (*simgrid_config)[name].set_value<T>(std::move(value));
380 }
381
382 template XBT_PUBLIC void set_value<int>(const char* name, int value);
383 template XBT_PUBLIC void set_value<double>(const char* name, double value);
384 template XBT_PUBLIC void set_value<bool>(const char* name, bool value);
385 template XBT_PUBLIC void set_value<std::string>(const char* name, std::string value);
386
387 void set_as_string(const char* name, const std::string& value)
388 {
389   (*simgrid_config)[name].set_string_value(value.c_str());
390 }
391
392 void set_parse(const std::string& opt)
393 {
394   std::string options(opt);
395   XBT_DEBUG("List to parse and set:'%s'", options.c_str());
396   while (not options.empty()) {
397     XBT_DEBUG("Still to parse and set: '%s'", options.c_str());
398
399     // skip separators
400     size_t pos = options.find_first_not_of(" \t\n,");
401     options.erase(0, pos);
402     // find option
403     pos              = options.find_first_of(" \t\n,");
404     std::string name = options.substr(0, pos);
405     options.erase(0, pos);
406     XBT_DEBUG("parse now:'%s'; parse later:'%s'", name.c_str(), options.c_str());
407
408     if (name.empty())
409       continue;
410
411     pos = name.find(':');
412     xbt_assert(pos != std::string::npos, "Option '%s' badly formatted. Should be of the form 'name:value'",
413                name.c_str());
414
415     std::string val = name.substr(pos + 1);
416     name.erase(pos);
417
418     const std::string path("path");
419     if (name.compare(0, path.length(), path) != 0)
420       XBT_INFO("Configuration change: Set '%s' to '%s'", name.c_str(), val.c_str());
421
422     set_as_string(name.c_str(), val);
423   }
424 }
425
426 // ***** get_value *****
427
428 template <class T> XBT_PUBLIC T const& get_value(const std::string& name)
429 {
430   return (*simgrid_config)[name].get_value<T>();
431 }
432
433 template XBT_PUBLIC int const& get_value<int>(const std::string& name);
434 template XBT_PUBLIC double const& get_value<double>(const std::string& name);
435 template XBT_PUBLIC bool const& get_value<bool>(const std::string& name);
436 template XBT_PUBLIC std::string const& get_value<std::string>(const std::string& name);
437
438 // ***** alias *****
439
440 void alias(const char* realname, std::initializer_list<const char*> aliases)
441 {
442   for (auto const& aliasname : aliases)
443     simgrid_config->alias(realname, aliasname);
444 }
445
446 // ***** declare_flag *****
447
448 template <class T>
449 XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, T value,
450                              std::function<void(const T&)> callback)
451 {
452   if (simgrid_config == nullptr)
453     simgrid_config = new simgrid::config::Config();
454   simgrid_config->register_option<T>(name, description, std::move(value), std::move(callback));
455 }
456
457 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, int value,
458                                       std::function<void(int const&)> callback);
459 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, double value,
460                                       std::function<void(double const&)> callback);
461 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, bool value,
462                                       std::function<void(bool const&)> callback);
463 template XBT_PUBLIC void declare_flag(const std::string& name, const std::string& description, std::string value,
464                                       std::function<void(std::string const&)> callback);
465
466 void finalize()
467 {
468   delete simgrid_config;
469   simgrid_config = nullptr;
470 }
471
472 void show_aliases()
473 {
474   simgrid_config->show_aliases();
475 }
476
477 void help()
478 {
479   simgrid_config->help();
480 }
481 }
482 }
483
484 /*----[ Setting ]---------------------------------------------------------*/
485
486 /** @brief Set an integer value to \a name within \a cfg
487  *
488  * @param key the name of the variable
489  * @param value the value of the variable
490  */
491 void sg_cfg_set_int(const char* key, int value)
492 {
493   (*simgrid_config)[key].set_value<int>(value);
494 }
495
496 /** @brief Set or add a double value to \a name within \a cfg
497  *
498  * @param key the name of the variable
499  * @param value the double to set
500  */
501 void sg_cfg_set_double(const char* key, double value)
502 {
503   (*simgrid_config)[key].set_value<double>(value);
504 }
505
506 /** @brief Set or add a string value to \a name within \a cfg
507  *
508  * @param key the name of the variable
509  * @param value the value to be added
510  *
511  */
512 void sg_cfg_set_string(const char* key, const char* value)
513 {
514   (*simgrid_config)[key].set_value<std::string>(value);
515 }
516
517 /** @brief Set or add a boolean value to \a name within \a cfg
518  *
519  * @param key the name of the variable
520  * @param value the value of the variable
521  */
522 void sg_cfg_set_boolean(const char* key, const char* value)
523 {
524   (*simgrid_config)[key].set_value<bool>(simgrid::config::parse_bool(value));
525 }
526
527 /*----[ Getting ]---------------------------------------------------------*/
528 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
529  *
530  * @param key the name of the variable
531  *
532  * Returns the first value from the config set under the given name.
533  */
534 int sg_cfg_get_int(const char* key)
535 {
536   return (*simgrid_config)[key].get_value<int>();
537 }
538
539 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
540  *
541  * @param key the name of the variable
542  *
543  * Returns the first value from the config set under the given name.
544  */
545 double sg_cfg_get_double(const char* key)
546 {
547   return (*simgrid_config)[key].get_value<double>();
548 }
549
550 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
551  *
552  * @param key the name of the variable
553  *
554  * Returns the first value from the config set under the given name.
555  * If there is more than one value, it will issue a warning.
556  */
557 int sg_cfg_get_boolean(const char* key)
558 {
559   return (*simgrid_config)[key].get_value<bool>() ? 1 : 0;
560 }