HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
CLI11.h
Go to the documentation of this file.
1 // CLI11: Version 2.3.1
2 // Originally designed by Henry Schreiner
3 // https://github.com/CLIUtils/CLI11
4 //
5 // This is a standalone header file generated by MakeSingleHeader.py in CLI11/scripts
6 // from: v2.3.1
7 //
8 // CLI11 2.3.1 Copyright (c) 2017-2022 University of Cincinnati, developed by Henry
9 // Schreiner under NSF AWARD 1414736. All rights reserved.
10 //
11 // Redistribution and use in source and binary forms of CLI11, with or without
12 // modification, are permitted provided that the following conditions are met:
13 //
14 // 1. Redistributions of source code must retain the above copyright notice, this
15 // list of conditions and the following disclaimer.
16 // 2. Redistributions in binary form must reproduce the above copyright notice,
17 // this list of conditions and the following disclaimer in the documentation
18 // and/or other materials provided with the distribution.
19 // 3. Neither the name of the copyright holder nor the names of its contributors
20 // may be used to endorse or promote products derived from this software without
21 // specific prior written permission.
22 //
23 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24 // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
27 // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
30 // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 
34 // This header is not meant to be included in a .h file, to guard against
35 // conflicts if a program includes their own CLI11 header and then transitively
36 // includes this header.
37 #ifdef PXR_CLI11_H
38 #error This file should only be included once in any given source (.cpp) file.
39 #endif
40 #define PXR_CLI11_H
41 
42 #pragma once
43 
44 // Standard combined includes:
45 #include <functional>
46 #include <locale>
47 #include <cstdint>
48 #include <iomanip>
49 #include <memory>
50 #include <exception>
51 #include <stdexcept>
52 #include <string>
53 #include <vector>
54 #include <iterator>
55 #include <algorithm>
56 #include <sstream>
57 #include <cmath>
58 #include <type_traits>
59 #include <limits>
60 #include <set>
61 #include <utility>
62 #include <map>
63 #include <iostream>
64 #include <numeric>
65 #include <fstream>
66 #include <tuple>
67 
68 #include "pxr/pxr.h"
69 
70 // Guard against possible conflicts if this header is included in the
71 // same file as another CLI11 header.
72 #ifdef CLI11_VERSION
73 #error This file cannot be included alongside a different CLI11 header.
74 #endif
75 
76 #define CLI11_VERSION_MAJOR 2
77 #define CLI11_VERSION_MINOR 3
78 #define CLI11_VERSION_PATCH 1
79 #define CLI11_VERSION "2.3.1"
80 
81 
82 
83 
84 // The following version macro is very similar to the one in pybind11
85 #if !(defined(_MSC_VER) && __cplusplus == 199711L) && !defined(__INTEL_COMPILER)
86 #if __cplusplus >= 201402L
87 #define CLI11_CPP14
88 #if __cplusplus >= 201703L
89 #define CLI11_CPP17
90 #if __cplusplus > 201703L
91 #define CLI11_CPP20
92 #endif
93 #endif
94 #endif
95 #elif defined(_MSC_VER) && __cplusplus == 199711L
96 // MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully implemented)
97 // Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3 or newer
98 #if _MSVC_LANG >= 201402L
99 #define CLI11_CPP14
100 #if _MSVC_LANG > 201402L && _MSC_VER >= 1910
101 #define CLI11_CPP17
102 #if _MSVC_LANG > 201703L && _MSC_VER >= 1910
103 #define CLI11_CPP20
104 #endif
105 #endif
106 #endif
107 #endif
108 
109 #if defined(CLI11_CPP14)
110 #define CLI11_DEPRECATED(reason) [[deprecated(reason)]]
111 #elif defined(_MSC_VER)
112 #define CLI11_DEPRECATED(reason) __declspec(deprecated(reason))
113 #else
114 #define CLI11_DEPRECATED(reason) __attribute__((deprecated(reason)))
115 #endif
116 
117 // GCC < 10 doesn't ignore this in unevaluated contexts
118 #if !defined(CLI11_CPP17) || \
119  (defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER) && __GNUC__ < 10 && __GNUC__ > 4)
120 #define CLI11_NODISCARD
121 #else
122 #define CLI11_NODISCARD [[nodiscard]]
123 #endif
124 
125 /** detection of rtti */
126 #ifndef CLI11_USE_STATIC_RTTI
127 #if(defined(_HAS_STATIC_RTTI) && _HAS_STATIC_RTTI)
128 #define CLI11_USE_STATIC_RTTI 1
129 #elif defined(__cpp_rtti)
130 #if(defined(_CPPRTTI) && _CPPRTTI == 0)
131 #define CLI11_USE_STATIC_RTTI 1
132 #else
133 #define CLI11_USE_STATIC_RTTI 0
134 #endif
135 #elif(defined(__GCC_RTTI) && __GXX_RTTI)
136 #define CLI11_USE_STATIC_RTTI 0
137 #else
138 #define CLI11_USE_STATIC_RTTI 1
139 #endif
140 #endif
141 
142 /** Inline macro **/
143 #ifdef CLI11_COMPILE
144 #define CLI11_INLINE
145 #else
146 #define CLI11_INLINE inline
147 #endif
148 
149 
150 
151 // C standard library
152 // Only needed for existence checking
153 #if defined CLI11_CPP17 && defined __has_include && !defined CLI11_HAS_FILESYSTEM
154 #if __has_include(<filesystem>)
155 // Filesystem cannot be used if targeting macOS < 10.15
156 #if defined __MAC_OS_X_VERSION_MIN_REQUIRED && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500
157 #define CLI11_HAS_FILESYSTEM 0
158 #elif defined(__wasi__)
159 // As of wasi-sdk-14, filesystem is not implemented
160 #define CLI11_HAS_FILESYSTEM 0
161 #else
162 #include <filesystem>
163 #if defined __cpp_lib_filesystem && __cpp_lib_filesystem >= 201703
164 #if defined _GLIBCXX_RELEASE && _GLIBCXX_RELEASE >= 9
165 #define CLI11_HAS_FILESYSTEM 1
166 #elif defined(__GLIBCXX__)
167 // if we are using gcc and Version <9 default to no filesystem
168 #define CLI11_HAS_FILESYSTEM 0
169 #else
170 #define CLI11_HAS_FILESYSTEM 1
171 #endif
172 #else
173 #define CLI11_HAS_FILESYSTEM 0
174 #endif
175 #endif
176 #endif
177 #endif
178 
179 #if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
180 #include <filesystem> // NOLINT(build/include)
181 #else
182 #include <sys/stat.h>
183 #include <sys/types.h>
184 #endif
185 
186 // Isolate symbols from other translation units that may have included their
187 // own copy of CLI11 by wrapping in the pxr namespace as well as a secondary
188 // hard-coded namespace. The latter is needed in case the outer pxr namespace
189 // has been disabled.
191 
192 namespace pxr_CLI {
193 
194 namespace CLI {
195 
196 
197 /// Include the items in this namespace to get free conversion of enums to/from streams.
198 /// (This is available inside CLI as well, so CLI11 will use this without a using statement).
199 namespace enums {
200 
201 /// output streaming for enumerations
203 std::ostream &operator<<(std::ostream &in, const T &item) {
204  // make sure this is out of the detail namespace otherwise it won't be found when needed
206 }
207 
208 } // namespace enums
209 
210 /// Export to CLI namespace
211 using enums::operator<<;
212 
213 namespace detail {
214 /// a constant defining an expected max vector size defined to be a big number that could be multiplied by 4 and not
215 /// produce overflow for some expected uses
216 constexpr int expected_max_vector_size{1 << 29};
217 // Based on http://stackoverflow.com/questions/236129/split-a-string-in-c
218 /// Split a string by a delim
219 CLI11_INLINE std::vector<std::string> split(const std::string &s, char delim);
220 
221 /// Simple function to join a string
222 template <typename T> std::string join(const T &v, std::string delim = ",") {
223  std::ostringstream s;
224  auto beg = std::begin(v);
225  auto end = std::end(v);
226  if(beg != end)
227  s << *beg++;
228  while(beg != end) {
229  s << delim << *beg++;
230  }
231  return s.str();
232 }
233 
234 /// Simple function to join a string from processed elements
235 template <typename T,
236  typename Callable,
238 std::string join(const T &v, Callable func, std::string delim = ",") {
239  std::ostringstream s;
240  auto beg = std::begin(v);
241  auto end = std::end(v);
242  auto loc = s.tellp();
243  while(beg != end) {
244  auto nloc = s.tellp();
245  if(nloc > loc) {
246  s << delim;
247  loc = nloc;
248  }
249  s << func(*beg++);
250  }
251  return s.str();
252 }
253 
254 /// Join a string in reverse order
255 template <typename T> std::string rjoin(const T &v, std::string delim = ",") {
256  std::ostringstream s;
257  for(std::size_t start = 0; start < v.size(); start++) {
258  if(start > 0)
259  s << delim;
260  s << v[v.size() - start - 1];
261  }
262  return s.str();
263 }
264 
265 // Based roughly on http://stackoverflow.com/questions/25829143/c-trim-whitespace-from-a-string
266 
267 /// Trim whitespace from left of string
269 
270 /// Trim anything from left of string
272 
273 /// Trim whitespace from right of string
275 
276 /// Trim anything from right of string
278 
279 /// Trim whitespace from string
280 inline std::string &trim(std::string &str) { return ltrim(rtrim(str)); }
281 
282 /// Trim anything from string
283 inline std::string &trim(std::string &str, const std::string filter) { return ltrim(rtrim(str, filter), filter); }
284 
285 /// Make a copy of the string and then trim it
286 inline std::string trim_copy(const std::string &str) {
287  std::string s = str;
288  return trim(s);
289 }
290 
291 /// remove quotes at the front and back of a string either '"' or '\''
293 
294 /// Add a leader to the beginning of all new lines (nothing is added
295 /// at the start of the first line). `"; "` would be for ini files
296 ///
297 /// Can't use Regex, or this would be a subs.
299 
300 /// Make a copy of the string and then trim it, any filter string can be used (any char in string is filtered)
301 inline std::string trim_copy(const std::string &str, const std::string &filter) {
302  std::string s = str;
303  return trim(s, filter);
304 }
305 /// Print a two part "help" string
306 CLI11_INLINE std::ostream &
307 format_help(std::ostream &out, std::string name, const std::string &description, std::size_t wid);
308 
309 /// Print subcommand aliases
310 CLI11_INLINE std::ostream &format_aliases(std::ostream &out, const std::vector<std::string> &aliases, std::size_t wid);
311 
312 /// Verify the first character of an option
313 /// - is a trigger character, ! has special meaning and new lines would just be annoying to deal with
314 template <typename T> bool valid_first_char(T c) { return ((c != '-') && (c != '!') && (c != ' ') && c != '\n'); }
315 
316 /// Verify following characters of an option
317 template <typename T> bool valid_later_char(T c) {
318  // = and : are value separators, { has special meaning for option defaults,
319  // and \n would just be annoying to deal with in many places allowing space here has too much potential for
320  // inadvertent entry errors and bugs
321  return ((c != '=') && (c != ':') && (c != '{') && (c != ' ') && c != '\n');
322 }
323 
324 /// Verify an option/subcommand name
326 
327 /// Verify an app name
328 inline bool valid_alias_name_string(const std::string &str) {
329  static const std::string badChars(std::string("\n") + '\0');
330  return (str.find_first_of(badChars) == std::string::npos);
331 }
332 
333 /// check if a string is a container segment separator (empty or "%%")
334 inline bool is_separator(const std::string &str) {
335  static const std::string sep("%%");
336  return (str.empty() || str == sep);
337 }
338 
339 /// Verify that str consists of letters only
340 inline bool isalpha(const std::string &str) {
341  return std::all_of(str.begin(), str.end(), [](char c) { return std::isalpha(c, std::locale()); });
342 }
343 
344 /// Return a lower case version of a string
347  return std::tolower(x, std::locale());
348  });
349  return str;
350 }
351 
352 /// remove underscores from a string
354  str.erase(std::remove(std::begin(str), std::end(str), '_'), std::end(str));
355  return str;
356 }
357 
358 /// Find and replace a substring with another substring
360 
361 /// check if the flag definitions has possible false flags
363  return (flags.find_first_of("{!") != std::string::npos);
364 }
365 
367 
368 /// Check if a string is a member of a list of strings and optionally ignore case or ignore underscores
370  const std::vector<std::string> names,
371  bool ignore_case = false,
372  bool ignore_underscore = false);
373 
374 /// Find a trigger string and call a modify callable function that takes the current string and starting position of the
375 /// trigger and returns the position in the string to search for the next trigger string
376 template <typename Callable> inline std::string find_and_modify(std::string str, std::string trigger, Callable modify) {
377  std::size_t start_pos = 0;
378  while((start_pos = str.find(trigger, start_pos)) != std::string::npos) {
379  start_pos = modify(str, start_pos);
380  }
381  return str;
382 }
383 
384 /// Split a string '"one two" "three"' into 'one two', 'three'
385 /// Quote characters can be ` ' or "
386 CLI11_INLINE std::vector<std::string> split_up(std::string str, char delimiter = '\0');
387 
388 /// This function detects an equal or colon followed by an escaped quote after an argument
389 /// then modifies the string to replace the equality with a space. This is needed
390 /// to allow the split up function to work properly and is intended to be used with the find_and_modify function
391 /// the return value is the offset+1 which is required by the find_and_modify function.
392 CLI11_INLINE std::size_t escape_detect(std::string &str, std::size_t offset);
393 
394 /// Add quotes if the string contains spaces
396 
397 } // namespace detail
398 
399 
400 
401 
402 namespace detail {
403 CLI11_INLINE std::vector<std::string> split(const std::string &s, char delim) {
404  std::vector<std::string> elems;
405  // Check to see if empty string, give consistent result
406  if(s.empty()) {
407  elems.emplace_back();
408  } else {
409  std::stringstream ss;
410  ss.str(s);
411  std::string item;
412  while(std::getline(ss, item, delim)) {
413  elems.push_back(item);
414  }
415  }
416  return elems;
417 }
418 
420  auto it = std::find_if(str.begin(), str.end(), [](char ch) { return !std::isspace<char>(ch, std::locale()); });
421  str.erase(str.begin(), it);
422  return str;
423 }
424 
426  auto it = std::find_if(str.begin(), str.end(), [&filter](char ch) { return filter.find(ch) == std::string::npos; });
427  str.erase(str.begin(), it);
428  return str;
429 }
430 
432  auto it = std::find_if(str.rbegin(), str.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale()); });
433  str.erase(it.base(), str.end());
434  return str;
435 }
436 
438  auto it =
439  std::find_if(str.rbegin(), str.rend(), [&filter](char ch) { return filter.find(ch) == std::string::npos; });
440  str.erase(it.base(), str.end());
441  return str;
442 }
443 
445  if(str.length() > 1 && (str.front() == '"' || str.front() == '\'')) {
446  if(str.front() == str.back()) {
447  str.pop_back();
448  str.erase(str.begin(), str.begin() + 1);
449  }
450  }
451  return str;
452 }
453 
455  std::string::size_type n = 0;
456  while(n != std::string::npos && n < input.size()) {
457  n = input.find('\n', n);
458  if(n != std::string::npos) {
459  input = input.substr(0, n + 1) + leader + input.substr(n + 1);
460  n += leader.size();
461  }
462  }
463  return input;
464 }
465 
466 CLI11_INLINE std::ostream &
467 format_help(std::ostream &out, std::string name, const std::string &description, std::size_t wid) {
468  name = " " + name;
469  out << std::setw(static_cast<int>(wid)) << std::left << name;
470  if(!description.empty()) {
471  if(name.length() >= wid)
472  out << "\n" << std::setw(static_cast<int>(wid)) << "";
473  for(const char c : description) {
474  out.put(c);
475  if(c == '\n') {
476  out << std::setw(static_cast<int>(wid)) << "";
477  }
478  }
479  }
480  out << "\n";
481  return out;
482 }
483 
484 CLI11_INLINE std::ostream &format_aliases(std::ostream &out, const std::vector<std::string> &aliases, std::size_t wid) {
485  if(!aliases.empty()) {
486  out << std::setw(static_cast<int>(wid)) << " aliases: ";
487  bool front = true;
488  for(const auto &alias : aliases) {
489  if(!front) {
490  out << ", ";
491  } else {
492  front = false;
493  }
494  out << detail::fix_newlines(" ", alias);
495  }
496  out << "\n";
497  }
498  return out;
499 }
500 
502  if(str.empty() || !valid_first_char(str[0])) {
503  return false;
504  }
505  auto e = str.end();
506  for(auto c = str.begin() + 1; c != e; ++c)
507  if(!valid_later_char(*c))
508  return false;
509  return true;
510 }
511 
513 
514  std::size_t start_pos = 0;
515 
516  while((start_pos = str.find(from, start_pos)) != std::string::npos) {
517  str.replace(start_pos, from.length(), to);
518  start_pos += to.length();
519  }
520 
521  return str;
522 }
523 
525  auto loc = flags.find_first_of('{', 2);
526  while(loc != std::string::npos) {
527  auto finish = flags.find_first_of("},", loc + 1);
528  if((finish != std::string::npos) && (flags[finish] == '}')) {
529  flags.erase(flags.begin() + static_cast<std::ptrdiff_t>(loc),
530  flags.begin() + static_cast<std::ptrdiff_t>(finish) + 1);
531  }
532  loc = flags.find_first_of('{', loc + 1);
533  }
534  flags.erase(std::remove(flags.begin(), flags.end(), '!'), flags.end());
535 }
536 
537 CLI11_INLINE std::ptrdiff_t
538 find_member(std::string name, const std::vector<std::string> names, bool ignore_case, bool ignore_underscore) {
539  auto it = std::end(names);
540  if(ignore_case) {
541  if(ignore_underscore) {
543  it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
544  return detail::to_lower(detail::remove_underscore(local_name)) == name;
545  });
546  } else {
547  name = detail::to_lower(name);
548  it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
549  return detail::to_lower(local_name) == name;
550  });
551  }
552 
553  } else if(ignore_underscore) {
554  name = detail::remove_underscore(name);
555  it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
556  return detail::remove_underscore(local_name) == name;
557  });
558  } else {
559  it = std::find(std::begin(names), std::end(names), name);
560  }
561 
562  return (it != std::end(names)) ? (it - std::begin(names)) : (-1);
563 }
564 
565 CLI11_INLINE std::vector<std::string> split_up(std::string str, char delimiter) {
566 
567  const std::string delims("\'\"`");
568  auto find_ws = [delimiter](char ch) {
569  return (delimiter == '\0') ? std::isspace<char>(ch, std::locale()) : (ch == delimiter);
570  };
571  trim(str);
572 
573  std::vector<std::string> output;
574  bool embeddedQuote = false;
575  char keyChar = ' ';
576  while(!str.empty()) {
577  if(delims.find_first_of(str[0]) != std::string::npos) {
578  keyChar = str[0];
579  auto end = str.find_first_of(keyChar, 1);
580  while((end != std::string::npos) && (str[end - 1] == '\\')) { // deal with escaped quotes
581  end = str.find_first_of(keyChar, end + 1);
582  embeddedQuote = true;
583  }
584  if(end != std::string::npos) {
585  output.push_back(str.substr(1, end - 1));
586  if(end + 2 < str.size()) {
587  str = str.substr(end + 2);
588  } else {
589  str.clear();
590  }
591 
592  } else {
593  output.push_back(str.substr(1));
594  str = "";
595  }
596  } else {
597  auto it = std::find_if(std::begin(str), std::end(str), find_ws);
598  if(it != std::end(str)) {
599  std::string value = std::string(str.begin(), it);
600  output.push_back(value);
601  str = std::string(it + 1, str.end());
602  } else {
603  output.push_back(str);
604  str = "";
605  }
606  }
607  // transform any embedded quotes into the regular character
608  if(embeddedQuote) {
609  output.back() = find_and_replace(output.back(), std::string("\\") + keyChar, std::string(1, keyChar));
610  embeddedQuote = false;
611  }
612  trim(str);
613  }
614  return output;
615 }
616 
617 CLI11_INLINE std::size_t escape_detect(std::string &str, std::size_t offset) {
618  auto next = str[offset + 1];
619  if((next == '\"') || (next == '\'') || (next == '`')) {
620  auto astart = str.find_last_of("-/ \"\'`", offset - 1);
621  if(astart != std::string::npos) {
622  if(str[astart] == ((str[offset] == '=') ? '-' : '/'))
623  str[offset] = ' '; // interpret this as a space so the split_up works properly
624  }
625  }
626  return offset + 1;
627 }
628 
630  if((str.front() != '"' && str.front() != '\'') || str.front() != str.back()) {
631  char quote = str.find('"') < str.find('\'') ? '\'' : '"';
632  if(str.find(' ') != std::string::npos) {
633  str.insert(0, 1, quote);
634  str.append(1, quote);
635  }
636  }
637  return str;
638 }
639 
640 } // namespace detail
641 
642 
643 
644 // Use one of these on all error classes.
645 // These are temporary and are undef'd at the end of this file.
646 #define CLI11_ERROR_DEF(parent, name) \
647  protected: \
648  name(std::string ename, std::string msg, int exit_code) : parent(std::move(ename), std::move(msg), exit_code) {} \
649  name(std::string ename, std::string msg, ExitCodes exit_code) \
650  : parent(std::move(ename), std::move(msg), exit_code) {} \
651  \
652  public: \
653  name(std::string msg, ExitCodes exit_code) : parent(#name, std::move(msg), exit_code) {} \
654  name(std::string msg, int exit_code) : parent(#name, std::move(msg), exit_code) {}
655 
656 // This is added after the one above if a class is used directly and builds its own message
657 #define CLI11_ERROR_SIMPLE(name) \
658  explicit name(std::string msg) : name(#name, msg, ExitCodes::name) {}
659 
660 /// These codes are part of every error in CLI. They can be obtained from e using e.exit_code or as a quick shortcut,
661 /// int values from e.get_error_code().
662 enum class ExitCodes {
663  Success = 0,
664  IncorrectConstruction = 100,
667  FileError,
673  ExtrasError,
674  ConfigError,
675  InvalidError,
679  BaseClass = 127
680 };
681 
682 // Error definitions
683 
684 /// @defgroup error_group Errors
685 /// @brief Errors thrown by CLI11
686 ///
687 /// These are the errors that can be thrown. Some of them, like CLI::Success, are not really errors.
688 /// @{
689 
690 /// All errors derive from this one
691 class Error : public std::runtime_error {
692  int actual_exit_code;
693  std::string error_name{"Error"};
694 
695  public:
696  CLI11_NODISCARD int get_exit_code() const { return actual_exit_code; }
697 
698  CLI11_NODISCARD std::string get_name() const { return error_name; }
699 
700  Error(std::string name, std::string msg, int exit_code = static_cast<int>(ExitCodes::BaseClass))
701  : runtime_error(msg), actual_exit_code(exit_code), error_name(std::move(name)) {}
702 
703  Error(std::string name, std::string msg, ExitCodes exit_code) : Error(name, msg, static_cast<int>(exit_code)) {}
704 };
705 
706 // Note: Using Error::Error constructors does not work on GCC 4.7
707 
708 /// Construction errors (not in parsing)
709 class ConstructionError : public Error {
711 };
712 
713 /// Thrown when an option is set to conflicting values (non-vector and multi args, for example)
717  static IncorrectConstruction PositionalFlag(std::string name) {
718  return IncorrectConstruction(name + ": Flags cannot be positional");
719  }
720  static IncorrectConstruction Set0Opt(std::string name) {
721  return IncorrectConstruction(name + ": Cannot set 0 expected, use a flag instead");
722  }
723  static IncorrectConstruction SetFlag(std::string name) {
724  return IncorrectConstruction(name + ": Cannot set an expected number for flags");
725  }
726  static IncorrectConstruction ChangeNotVector(std::string name) {
727  return IncorrectConstruction(name + ": You can only change the expected arguments for vectors");
728  }
729  static IncorrectConstruction AfterMultiOpt(std::string name) {
730  return IncorrectConstruction(
731  name + ": You can't change expected arguments after you've changed the multi option policy!");
732  }
733  static IncorrectConstruction MissingOption(std::string name) {
734  return IncorrectConstruction("Option " + name + " is not defined");
735  }
737  return IncorrectConstruction(name + ": multi_option_policy only works for flags and exact value options");
738  }
739 };
740 
741 /// Thrown on construction of a bad name
745  static BadNameString OneCharName(std::string name) { return BadNameString("Invalid one char name: " + name); }
746  static BadNameString BadLongName(std::string name) { return BadNameString("Bad long name: " + name); }
747  static BadNameString DashesOnly(std::string name) {
748  return BadNameString("Must have a name, not just dashes: " + name);
749  }
750  static BadNameString MultiPositionalNames(std::string name) {
751  return BadNameString("Only one positional name allowed, remove: " + name);
752  }
753 };
754 
755 /// Thrown when an option already exists
759  : OptionAlreadyAdded(name + " is already added", ExitCodes::OptionAlreadyAdded) {}
760  static OptionAlreadyAdded Requires(std::string name, std::string other) {
761  return {name + " requires " + other, ExitCodes::OptionAlreadyAdded};
762  }
763  static OptionAlreadyAdded Excludes(std::string name, std::string other) {
764  return {name + " excludes " + other, ExitCodes::OptionAlreadyAdded};
765  }
766 };
767 
768 // Parsing errors
769 
770 /// Anything that can error in Parse
771 class ParseError : public Error {
773 };
774 
775 // Not really "errors"
776 
777 /// This is a successful completion on parsing, supposed to exit
778 class Success : public ParseError {
780  Success() : Success("Successfully completed, should be caught and quit", ExitCodes::Success) {}
781 };
782 
783 /// -h or --help on command line
784 class CallForHelp : public Success {
786  CallForHelp() : CallForHelp("This should be caught in your main function, see examples", ExitCodes::Success) {}
787 };
788 
789 /// Usually something like --help-all on command line
790 class CallForAllHelp : public Success {
793  : CallForAllHelp("This should be caught in your main function, see examples", ExitCodes::Success) {}
794 };
795 
796 /// -v or --version on command line
797 class CallForVersion : public Success {
800  : CallForVersion("This should be caught in your main function, see examples", ExitCodes::Success) {}
801 };
802 
803 /// Does not output a diagnostic in CLI11_PARSE, but allows main() to return with a specific error code.
804 class RuntimeError : public ParseError {
806  explicit RuntimeError(int exit_code = 1) : RuntimeError("Runtime error", exit_code) {}
807 };
808 
809 /// Thrown when parsing an INI file and it is missing
810 class FileError : public ParseError {
813  static FileError Missing(std::string name) { return FileError(name + " was not readable (missing?)"); }
814 };
815 
816 /// Thrown when conversion call back fails, such as when an int fails to coerce to a string
817 class ConversionError : public ParseError {
821  : ConversionError("The value " + member + " is not an allowed value for " + name) {}
822  ConversionError(std::string name, std::vector<std::string> results)
823  : ConversionError("Could not convert: " + name + " = " + detail::join(results)) {}
824  static ConversionError TooManyInputsFlag(std::string name) {
825  return ConversionError(name + ": too many inputs for a flag");
826  }
827  static ConversionError TrueFalse(std::string name) {
828  return ConversionError(name + ": Should be true/false or a number");
829  }
830 };
831 
832 /// Thrown when validation of results fails
833 class ValidationError : public ParseError {
836  explicit ValidationError(std::string name, std::string msg) : ValidationError(name + ": " + msg) {}
837 };
838 
839 /// Thrown when a required option is missing
840 class RequiredError : public ParseError {
842  explicit RequiredError(std::string name) : RequiredError(name + " is required", ExitCodes::RequiredError) {}
843  static RequiredError Subcommand(std::size_t min_subcom) {
844  if(min_subcom == 1) {
845  return RequiredError("A subcommand");
846  }
847  return {"Requires at least " + std::to_string(min_subcom) + " subcommands", ExitCodes::RequiredError};
848  }
849  static RequiredError
850  Option(std::size_t min_option, std::size_t max_option, std::size_t used, const std::string &option_list) {
851  if((min_option == 1) && (max_option == 1) && (used == 0))
852  return RequiredError("Exactly 1 option from [" + option_list + "]");
853  if((min_option == 1) && (max_option == 1) && (used > 1)) {
854  return {"Exactly 1 option from [" + option_list + "] is required and " + std::to_string(used) +
855  " were given",
857  }
858  if((min_option == 1) && (used == 0))
859  return RequiredError("At least 1 option from [" + option_list + "]");
860  if(used < min_option) {
861  return {"Requires at least " + std::to_string(min_option) + " options used and only " +
862  std::to_string(used) + "were given from [" + option_list + "]",
864  }
865  if(max_option == 1)
866  return {"Requires at most 1 options be given from [" + option_list + "]", ExitCodes::RequiredError};
867 
868  return {"Requires at most " + std::to_string(max_option) + " options be used and " + std::to_string(used) +
869  "were given from [" + option_list + "]",
871  }
872 };
873 
874 /// Thrown when the wrong number of arguments has been received
875 class ArgumentMismatch : public ParseError {
878  ArgumentMismatch(std::string name, int expected, std::size_t received)
879  : ArgumentMismatch(expected > 0 ? ("Expected exactly " + std::to_string(expected) + " arguments to " + name +
880  ", got " + std::to_string(received))
881  : ("Expected at least " + std::to_string(-expected) + " arguments to " + name +
882  ", got " + std::to_string(received)),
884 
885  static ArgumentMismatch AtLeast(std::string name, int num, std::size_t received) {
886  return ArgumentMismatch(name + ": At least " + std::to_string(num) + " required but received " +
887  std::to_string(received));
888  }
889  static ArgumentMismatch AtMost(std::string name, int num, std::size_t received) {
890  return ArgumentMismatch(name + ": At Most " + std::to_string(num) + " required but received " +
891  std::to_string(received));
892  }
893  static ArgumentMismatch TypedAtLeast(std::string name, int num, std::string type) {
894  return ArgumentMismatch(name + ": " + std::to_string(num) + " required " + type + " missing");
895  }
896  static ArgumentMismatch FlagOverride(std::string name) {
897  return ArgumentMismatch(name + " was given a disallowed flag override");
898  }
899  static ArgumentMismatch PartialType(std::string name, int num, std::string type) {
900  return ArgumentMismatch(name + ": " + type + " only partially specified: " + std::to_string(num) +
901  " required for each element");
902  }
903 };
904 
905 /// Thrown when a requires option is missing
906 class RequiresError : public ParseError {
908  RequiresError(std::string curname, std::string subname)
909  : RequiresError(curname + " requires " + subname, ExitCodes::RequiresError) {}
910 };
911 
912 /// Thrown when an excludes option is present
913 class ExcludesError : public ParseError {
915  ExcludesError(std::string curname, std::string subname)
916  : ExcludesError(curname + " excludes " + subname, ExitCodes::ExcludesError) {}
917 };
918 
919 /// Thrown when too many positionals or options are found
920 class ExtrasError : public ParseError {
922  explicit ExtrasError(std::vector<std::string> args)
923  : ExtrasError((args.size() > 1 ? "The following arguments were not expected: "
924  : "The following argument was not expected: ") +
925  detail::rjoin(args, " "),
927  ExtrasError(const std::string &name, std::vector<std::string> args)
928  : ExtrasError(name,
929  (args.size() > 1 ? "The following arguments were not expected: "
930  : "The following argument was not expected: ") +
931  detail::rjoin(args, " "),
933 };
934 
935 /// Thrown when extra values are found in an INI file
936 class ConfigError : public ParseError {
939  static ConfigError Extras(std::string item) { return ConfigError("INI was not able to parse " + item); }
940  static ConfigError NotConfigurable(std::string item) {
941  return ConfigError(item + ": This option is not allowed in a configuration file");
942  }
943 };
944 
945 /// Thrown when validation fails before parsing
946 class InvalidError : public ParseError {
948  explicit InvalidError(std::string name)
949  : InvalidError(name + ": Too many positional arguments with unlimited expected args", ExitCodes::InvalidError) {
950  }
951 };
952 
953 /// This is just a safety check to verify selection and parsing match - you should not ever see it
954 /// Strings are directly added to this error, but again, it should never be seen.
955 class HorribleError : public ParseError {
958 };
959 
960 // After parsing
961 
962 /// Thrown when counting a non-existent option
963 class OptionNotFound : public Error {
965  explicit OptionNotFound(std::string name) : OptionNotFound(name + " not found", ExitCodes::OptionNotFound) {}
966 };
967 
968 #undef CLI11_ERROR_DEF
969 #undef CLI11_ERROR_SIMPLE
970 
971 /// @}
972 
973 
974 
975 
976 // Type tools
977 
978 // Utilities for type enabling
979 namespace detail {
980 // Based generally on https://rmf.io/cxx11/almost-static-if
981 /// Simple empty scoped class
982 enum class enabler {};
983 
984 /// An instance to use in EnableIf
985 constexpr enabler dummy = {};
986 } // namespace detail
987 
988 /// A copy of enable_if_t from C++14, compatible with C++11.
989 ///
990 /// We could check to see if C++14 is being used, but it does not hurt to redefine this
991 /// (even Google does this: https://github.com/google/skia/blob/main/include/private/SkTLogic.h)
992 /// It is not in the std namespace anyway, so no harm done.
993 template <bool B, class T = void> using enable_if_t = typename std::enable_if<B, T>::type;
994 
995 /// A copy of std::void_t from C++17 (helper for C++11 and C++14)
996 template <typename... Ts> struct make_void { using type = void; };
997 
998 /// A copy of std::void_t from C++17 - same reasoning as enable_if_t, it does not hurt to redefine
999 template <typename... Ts> using void_t = typename make_void<Ts...>::type;
1000 
1001 /// A copy of std::conditional_t from C++14 - same reasoning as enable_if_t, it does not hurt to redefine
1002 template <bool B, class T, class F> using conditional_t = typename std::conditional<B, T, F>::type;
1003 
1004 /// Check to see if something is bool (fail check by default)
1005 template <typename T> struct is_bool : std::false_type {};
1006 
1007 /// Check to see if something is bool (true if actually a bool)
1008 template <> struct is_bool<bool> : std::true_type {};
1009 
1010 /// Check to see if something is a shared pointer
1011 template <typename T> struct is_shared_ptr : std::false_type {};
1012 
1013 /// Check to see if something is a shared pointer (True if really a shared pointer)
1014 template <typename T> struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
1015 
1016 /// Check to see if something is a shared pointer (True if really a shared pointer)
1017 template <typename T> struct is_shared_ptr<const std::shared_ptr<T>> : std::true_type {};
1018 
1019 /// Check to see if something is copyable pointer
1020 template <typename T> struct is_copyable_ptr {
1022 };
1023 
1024 /// This can be specialized to override the type deduction for IsMember.
1025 template <typename T> struct IsMemberType { using type = T; };
1026 
1027 /// The main custom type needed here is const char * should be a string.
1028 template <> struct IsMemberType<const char *> { using type = std::string; };
1029 
1030 namespace detail {
1031 
1032 // These are utilities for IsMember and other transforming objects
1033 
1034 /// Handy helper to access the element_type generically. This is not part of is_copyable_ptr because it requires that
1035 /// pointer_traits<T> be valid.
1036 
1037 /// not a pointer
1038 template <typename T, typename Enable = void> struct element_type { using type = T; };
1039 
1040 template <typename T> struct element_type<T, typename std::enable_if<is_copyable_ptr<T>::value>::type> {
1041  using type = typename std::pointer_traits<T>::element_type;
1042 };
1043 
1044 /// Combination of the element type and value type - remove pointer (including smart pointers) and get the value_type of
1045 /// the container
1046 template <typename T> struct element_value_type { using type = typename element_type<T>::type::value_type; };
1047 
1048 /// Adaptor for set-like structure: This just wraps a normal container in a few utilities that do almost nothing.
1049 template <typename T, typename _ = void> struct pair_adaptor : std::false_type {
1050  using value_type = typename T::value_type;
1053 
1054  /// Get the first value (really just the underlying value)
1055  template <typename Q> static auto first(Q &&pair_value) -> decltype(std::forward<Q>(pair_value)) {
1056  return std::forward<Q>(pair_value);
1057  }
1058  /// Get the second value (really just the underlying value)
1059  template <typename Q> static auto second(Q &&pair_value) -> decltype(std::forward<Q>(pair_value)) {
1060  return std::forward<Q>(pair_value);
1061  }
1062 };
1063 
1064 /// Adaptor for map-like structure (true version, must have key_type and mapped_type).
1065 /// This wraps a mapped container in a few utilities access it in a general way.
1066 template <typename T>
1068  T,
1069  conditional_t<false, void_t<typename T::value_type::first_type, typename T::value_type::second_type>, void>>
1070  : std::true_type {
1071  using value_type = typename T::value_type;
1074 
1075  /// Get the first value (really just the underlying value)
1076  template <typename Q> static auto first(Q &&pair_value) -> decltype(std::get<0>(std::forward<Q>(pair_value))) {
1077  return std::get<0>(std::forward<Q>(pair_value));
1078  }
1079  /// Get the second value (really just the underlying value)
1080  template <typename Q> static auto second(Q &&pair_value) -> decltype(std::get<1>(std::forward<Q>(pair_value))) {
1081  return std::get<1>(std::forward<Q>(pair_value));
1082  }
1083 };
1084 
1085 // Warning is suppressed due to "bug" in gcc<5.0 and gcc 7.0 with c++17 enabled that generates a Wnarrowing warning
1086 // in the unevaluated context even if the function that was using this wasn't used. The standard says narrowing in
1087 // brace initialization shouldn't be allowed but for backwards compatibility gcc allows it in some contexts. It is a
1088 // little fuzzy what happens in template constructs and I think that was something GCC took a little while to work out.
1089 // But regardless some versions of gcc generate a warning when they shouldn't from the following code so that should be
1090 // suppressed
1091 #ifdef __GNUC__
1092 #pragma GCC diagnostic push
1093 #pragma GCC diagnostic ignored "-Wnarrowing"
1094 #endif
1095 // check for constructibility from a specific type and copy assignable used in the parse detection
1096 template <typename T, typename C> class is_direct_constructible {
1097  template <typename TT, typename CC>
1098  static auto test(int, std::true_type) -> decltype(
1099 // NVCC warns about narrowing conversions here
1100 #ifdef __CUDACC__
1101 #pragma diag_suppress 2361
1102 #endif
1103  TT{std::declval<CC>()}
1104 #ifdef __CUDACC__
1105 #pragma diag_default 2361
1106 #endif
1107  ,
1108  std::is_move_assignable<TT>());
1109 
1110  template <typename TT, typename CC> static auto test(int, std::false_type) -> std::false_type;
1111 
1112  template <typename, typename> static auto test(...) -> std::false_type;
1113 
1114  public:
1115  static constexpr bool value = decltype(test<T, C>(0, typename std::is_constructible<T, C>::type()))::value;
1116 };
1117 #ifdef __GNUC__
1118 #pragma GCC diagnostic pop
1119 #endif
1120 
1121 // Check for output streamability
1122 // Based on https://stackoverflow.com/questions/22758291/how-can-i-detect-if-a-type-can-be-streamed-to-an-stdostream
1123 
1124 template <typename T, typename S = std::ostringstream> class is_ostreamable {
1125  template <typename TT, typename SS>
1126  static auto test(int) -> decltype(std::declval<SS &>() << std::declval<TT>(), std::true_type());
1127 
1128  template <typename, typename> static auto test(...) -> std::false_type;
1129 
1130  public:
1131  static constexpr bool value = decltype(test<T, S>(0))::value;
1132 };
1133 
1134 /// Check for input streamability
1135 template <typename T, typename S = std::istringstream> class is_istreamable {
1136  template <typename TT, typename SS>
1137  static auto test(int) -> decltype(std::declval<SS &>() >> std::declval<TT &>(), std::true_type());
1138 
1139  template <typename, typename> static auto test(...) -> std::false_type;
1140 
1141  public:
1142  static constexpr bool value = decltype(test<T, S>(0))::value;
1143 };
1144 
1145 /// Check for complex
1146 template <typename T> class is_complex {
1147  template <typename TT>
1148  static auto test(int) -> decltype(std::declval<TT>().real(), std::declval<TT>().imag(), std::true_type());
1149 
1150  template <typename> static auto test(...) -> std::false_type;
1151 
1152  public:
1153  static constexpr bool value = decltype(test<T>(0))::value;
1154 };
1155 
1156 /// Templated operation to get a value from a stream
1158 bool from_stream(const std::string &istring, T &obj) {
1159  std::istringstream is;
1160  is.str(istring);
1161  is >> obj;
1162  return !is.fail() && !is.rdbuf()->in_avail();
1163 }
1164 
1166 bool from_stream(const std::string & /*istring*/, T & /*obj*/) {
1167  return false;
1168 }
1169 
1170 // check to see if an object is a mutable container (fail by default)
1171 template <typename T, typename _ = void> struct is_mutable_container : std::false_type {};
1172 
1173 /// type trait to test if a type is a mutable container meaning it has a value_type, it has an iterator, a clear, and
1174 /// end methods and an insert function. And for our purposes we exclude std::string and types that can be constructed
1175 /// from a std::string
1176 template <typename T>
1178  T,
1179  conditional_t<false,
1180  void_t<typename T::value_type,
1181  decltype(std::declval<T>().end()),
1182  decltype(std::declval<T>().clear()),
1183  decltype(std::declval<T>().insert(std::declval<decltype(std::declval<T>().end())>(),
1184  std::declval<const typename T::value_type &>()))>,
1185  void>>
1186  : public conditional_t<std::is_constructible<T, std::string>::value, std::false_type, std::true_type> {};
1187 
1188 // check to see if an object is a mutable container (fail by default)
1189 template <typename T, typename _ = void> struct is_readable_container : std::false_type {};
1190 
1191 /// type trait to test if a type is a container meaning it has a value_type, it has an iterator, a clear, and an end
1192 /// methods and an insert function. And for our purposes we exclude std::string and types that can be constructed from
1193 /// a std::string
1194 template <typename T>
1196  T,
1197  conditional_t<false, void_t<decltype(std::declval<T>().end()), decltype(std::declval<T>().begin())>, void>>
1198  : public std::true_type {};
1199 
1200 // check to see if an object is a wrapper (fail by default)
1201 template <typename T, typename _ = void> struct is_wrapper : std::false_type {};
1202 
1203 // check if an object is a wrapper (it has a value_type defined)
1204 template <typename T>
1205 struct is_wrapper<T, conditional_t<false, void_t<typename T::value_type>, void>> : public std::true_type {};
1206 
1207 // Check for tuple like types, as in classes with a tuple_size type trait
1208 template <typename S> class is_tuple_like {
1209  template <typename SS>
1210  // static auto test(int)
1211  // -> decltype(std::conditional<(std::tuple_size<SS>::value > 0), std::true_type, std::false_type>::type());
1212  static auto test(int) -> decltype(std::tuple_size<typename std::decay<SS>::type>::value, std::true_type{});
1213  template <typename> static auto test(...) -> std::false_type;
1214 
1215  public:
1216  static constexpr bool value = decltype(test<S>(0))::value;
1217 };
1218 
1219 /// Convert an object to a string (directly forward if this can become a string)
1221 auto to_string(T &&value) -> decltype(std::forward<T>(value)) {
1222  return std::forward<T>(value);
1223 }
1224 
1225 /// Construct a string from the object
1226 template <typename T,
1229 std::string to_string(const T &value) {
1230  return std::string(value); // NOLINT(google-readability-casting)
1231 }
1232 
1233 /// Convert an object to a string (streaming must be supported for that type)
1234 template <typename T,
1239  std::stringstream stream;
1240  stream << value;
1241  return stream.str();
1242 }
1243 
1244 /// If conversion is not supported, return an empty string (streaming is not supported for that type)
1245 template <typename T,
1249 std::string to_string(T &&) {
1250  return {};
1251 }
1252 
1253 /// convert a readable container to a string
1254 template <typename T,
1258 std::string to_string(T &&variable) {
1259  auto cval = variable.begin();
1260  auto end = variable.end();
1261  if(cval == end) {
1262  return {"{}"};
1263  }
1264  std::vector<std::string> defaults;
1265  while(cval != end) {
1266  defaults.emplace_back(CLI::detail::to_string(*cval));
1267  ++cval;
1268  }
1269  return {"[" + detail::join(defaults) + "]"};
1270 }
1271 
1272 /// special template overload
1273 template <typename T1,
1274  typename T2,
1275  typename T,
1277 auto checked_to_string(T &&value) -> decltype(to_string(std::forward<T>(value))) {
1278  return to_string(std::forward<T>(value));
1279 }
1280 
1281 /// special template overload
1282 template <typename T1,
1283  typename T2,
1284  typename T,
1287  return std::string{};
1288 }
1289 /// get a string as a convertible value for arithmetic types
1291 std::string value_string(const T &value) {
1292  return std::to_string(value);
1293 }
1294 /// get a string as a convertible value for enumerations
1296 std::string value_string(const T &value) {
1297  return std::to_string(static_cast<typename std::underlying_type<T>::type>(value));
1298 }
1299 /// for other types just use the regular to_string function
1300 template <typename T,
1302 auto value_string(const T &value) -> decltype(to_string(value)) {
1303  return to_string(value);
1304 }
1305 
1306 /// template to get the underlying value type if it exists or use a default
1307 template <typename T, typename def, typename Enable = void> struct wrapped_type { using type = def; };
1308 
1309 /// Type size for regular object types that do not look like a tuple
1310 template <typename T, typename def> struct wrapped_type<T, def, typename std::enable_if<is_wrapper<T>::value>::type> {
1311  using type = typename T::value_type;
1312 };
1313 
1314 /// This will only trigger for actual void type
1315 template <typename T, typename Enable = void> struct type_count_base { static const int value{0}; };
1316 
1317 /// Type size for regular object types that do not look like a tuple
1318 template <typename T>
1320  typename std::enable_if<!is_tuple_like<T>::value && !is_mutable_container<T>::value &&
1321  !std::is_void<T>::value>::type> {
1322  static constexpr int value{1};
1323 };
1324 
1325 /// the base tuple size
1326 template <typename T>
1327 struct type_count_base<T, typename std::enable_if<is_tuple_like<T>::value && !is_mutable_container<T>::value>::type> {
1328  static constexpr int value{std::tuple_size<T>::value};
1329 };
1330 
1331 /// Type count base for containers is the type_count_base of the individual element
1332 template <typename T> struct type_count_base<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1334 };
1335 
1336 /// Set of overloads to get the type size of an object
1337 
1338 /// forward declare the subtype_count structure
1339 template <typename T> struct subtype_count;
1340 
1341 /// forward declare the subtype_count_min structure
1342 template <typename T> struct subtype_count_min;
1343 
1344 /// This will only trigger for actual void type
1345 template <typename T, typename Enable = void> struct type_count { static const int value{0}; };
1346 
1347 /// Type size for regular object types that do not look like a tuple
1348 template <typename T>
1349 struct type_count<T,
1350  typename std::enable_if<!is_wrapper<T>::value && !is_tuple_like<T>::value && !is_complex<T>::value &&
1351  !std::is_void<T>::value>::type> {
1352  static constexpr int value{1};
1353 };
1354 
1355 /// Type size for complex since it sometimes looks like a wrapper
1356 template <typename T> struct type_count<T, typename std::enable_if<is_complex<T>::value>::type> {
1357  static constexpr int value{2};
1358 };
1359 
1360 /// Type size of types that are wrappers,except complex and tuples(which can also be wrappers sometimes)
1361 template <typename T> struct type_count<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1363 };
1364 
1365 /// Type size of types that are wrappers,except containers complex and tuples(which can also be wrappers sometimes)
1366 template <typename T>
1367 struct type_count<T,
1368  typename std::enable_if<is_wrapper<T>::value && !is_complex<T>::value && !is_tuple_like<T>::value &&
1369  !is_mutable_container<T>::value>::type> {
1370  static constexpr int value{type_count<typename T::value_type>::value};
1371 };
1372 
1373 /// 0 if the index > tuple size
1374 template <typename T, std::size_t I>
1376  return 0;
1377 }
1378 
1379 /// Recursively generate the tuple type name
1380 template <typename T, std::size_t I>
1382  return subtype_count<typename std::tuple_element<I, T>::type>::value + tuple_type_size<T, I + 1>();
1383 }
1384 
1385 /// Get the type size of the sum of type sizes for all the individual tuple types
1386 template <typename T> struct type_count<T, typename std::enable_if<is_tuple_like<T>::value>::type> {
1387  static constexpr int value{tuple_type_size<T, 0>()};
1388 };
1389 
1390 /// definition of subtype count
1391 template <typename T> struct subtype_count {
1393 };
1394 
1395 /// This will only trigger for actual void type
1396 template <typename T, typename Enable = void> struct type_count_min { static const int value{0}; };
1397 
1398 /// Type size for regular object types that do not look like a tuple
1399 template <typename T>
1400 struct type_count_min<
1401  T,
1402  typename std::enable_if<!is_mutable_container<T>::value && !is_tuple_like<T>::value && !is_wrapper<T>::value &&
1403  !is_complex<T>::value && !std::is_void<T>::value>::type> {
1404  static constexpr int value{type_count<T>::value};
1405 };
1406 
1407 /// Type size for complex since it sometimes looks like a wrapper
1408 template <typename T> struct type_count_min<T, typename std::enable_if<is_complex<T>::value>::type> {
1409  static constexpr int value{1};
1410 };
1411 
1412 /// Type size min of types that are wrappers,except complex and tuples(which can also be wrappers sometimes)
1413 template <typename T>
1414 struct type_count_min<
1415  T,
1416  typename std::enable_if<is_wrapper<T>::value && !is_complex<T>::value && !is_tuple_like<T>::value>::type> {
1417  static constexpr int value{subtype_count_min<typename T::value_type>::value};
1418 };
1419 
1420 /// 0 if the index > tuple size
1421 template <typename T, std::size_t I>
1422 constexpr typename std::enable_if<I == type_count_base<T>::value, int>::type tuple_type_size_min() {
1423  return 0;
1424 }
1425 
1426 /// Recursively generate the tuple type name
1427 template <typename T, std::size_t I>
1428  constexpr typename std::enable_if < I<type_count_base<T>::value, int>::type tuple_type_size_min() {
1429  return subtype_count_min<typename std::tuple_element<I, T>::type>::value + tuple_type_size_min<T, I + 1>();
1430 }
1431 
1432 /// Get the type size of the sum of type sizes for all the individual tuple types
1433 template <typename T> struct type_count_min<T, typename std::enable_if<is_tuple_like<T>::value>::type> {
1434  static constexpr int value{tuple_type_size_min<T, 0>()};
1435 };
1436 
1437 /// definition of subtype count
1438 template <typename T> struct subtype_count_min {
1439  static constexpr int value{is_mutable_container<T>::value
1441  : type_count_min<T>::value};
1442 };
1443 
1444 /// This will only trigger for actual void type
1445 template <typename T, typename Enable = void> struct expected_count { static const int value{0}; };
1446 
1447 /// For most types the number of expected items is 1
1448 template <typename T>
1449 struct expected_count<T,
1450  typename std::enable_if<!is_mutable_container<T>::value && !is_wrapper<T>::value &&
1451  !std::is_void<T>::value>::type> {
1452  static constexpr int value{1};
1453 };
1454 /// number of expected items in a vector
1455 template <typename T> struct expected_count<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1456  static constexpr int value{expected_max_vector_size};
1457 };
1458 
1459 /// number of expected items in a vector
1460 template <typename T>
1461 struct expected_count<T, typename std::enable_if<!is_mutable_container<T>::value && is_wrapper<T>::value>::type> {
1462  static constexpr int value{expected_count<typename T::value_type>::value};
1463 };
1464 
1465 // Enumeration of the different supported categorizations of objects
1466 enum class object_category : int {
1467  char_value = 1,
1468  integral_value = 2,
1469  unsigned_integral = 4,
1470  enumeration = 6,
1471  boolean_value = 8,
1472  floating_point = 10,
1473  number_constructible = 12,
1474  double_constructible = 14,
1475  integer_constructible = 16,
1476  // string like types
1477  string_assignable = 23,
1478  string_constructible = 24,
1479  other = 45,
1480  // special wrapper or container types
1481  wrapper_value = 50,
1482  complex_number = 60,
1483  tuple_value = 70,
1484  container_value = 80,
1485 
1486 };
1487 
1488 /// Set of overloads to classify an object according to type
1489 
1490 /// some type that is not otherwise recognized
1491 template <typename T, typename Enable = void> struct classify_object {
1492  static constexpr object_category value{object_category::other};
1493 };
1494 
1495 /// Signed integers
1496 template <typename T>
1497 struct classify_object<
1498  T,
1499  typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, char>::value && std::is_signed<T>::value &&
1500  !is_bool<T>::value && !std::is_enum<T>::value>::type> {
1501  static constexpr object_category value{object_category::integral_value};
1502 };
1503 
1504 /// Unsigned integers
1505 template <typename T>
1506 struct classify_object<T,
1507  typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value &&
1508  !std::is_same<T, char>::value && !is_bool<T>::value>::type> {
1509  static constexpr object_category value{object_category::unsigned_integral};
1510 };
1511 
1512 /// single character values
1513 template <typename T>
1514 struct classify_object<T, typename std::enable_if<std::is_same<T, char>::value && !std::is_enum<T>::value>::type> {
1515  static constexpr object_category value{object_category::char_value};
1516 };
1517 
1518 /// Boolean values
1519 template <typename T> struct classify_object<T, typename std::enable_if<is_bool<T>::value>::type> {
1520  static constexpr object_category value{object_category::boolean_value};
1521 };
1522 
1523 /// Floats
1524 template <typename T> struct classify_object<T, typename std::enable_if<std::is_floating_point<T>::value>::type> {
1525  static constexpr object_category value{object_category::floating_point};
1526 };
1527 
1528 /// String and similar direct assignment
1529 template <typename T>
1530 struct classify_object<T,
1531  typename std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1532  std::is_assignable<T &, std::string>::value>::type> {
1533  static constexpr object_category value{object_category::string_assignable};
1534 };
1535 
1536 /// String and similar constructible and copy assignment
1537 template <typename T>
1538 struct classify_object<
1539  T,
1540  typename std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1541  !std::is_assignable<T &, std::string>::value && (type_count<T>::value == 1) &&
1542  std::is_constructible<T, std::string>::value>::type> {
1543  static constexpr object_category value{object_category::string_constructible};
1544 };
1545 
1546 /// Enumerations
1547 template <typename T> struct classify_object<T, typename std::enable_if<std::is_enum<T>::value>::type> {
1548  static constexpr object_category value{object_category::enumeration};
1549 };
1550 
1551 template <typename T> struct classify_object<T, typename std::enable_if<is_complex<T>::value>::type> {
1552  static constexpr object_category value{object_category::complex_number};
1553 };
1554 
1555 /// Handy helper to contain a bunch of checks that rule out many common types (integers, string like, floating point,
1556 /// vectors, and enumerations
1557 template <typename T> struct uncommon_type {
1562  std::true_type,
1563  std::false_type>::type;
1564  static constexpr bool value = type::value;
1565 };
1566 
1567 /// wrapper type
1568 template <typename T>
1569 struct classify_object<T,
1570  typename std::enable_if<(!is_mutable_container<T>::value && is_wrapper<T>::value &&
1571  !is_tuple_like<T>::value && uncommon_type<T>::value)>::type> {
1572  static constexpr object_category value{object_category::wrapper_value};
1573 };
1574 
1575 /// Assignable from double or int
1576 template <typename T>
1577 struct classify_object<T,
1578  typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1579  !is_wrapper<T>::value && is_direct_constructible<T, double>::value &&
1580  is_direct_constructible<T, int>::value>::type> {
1581  static constexpr object_category value{object_category::number_constructible};
1582 };
1583 
1584 /// Assignable from int
1585 template <typename T>
1586 struct classify_object<T,
1587  typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1588  !is_wrapper<T>::value && !is_direct_constructible<T, double>::value &&
1589  is_direct_constructible<T, int>::value>::type> {
1590  static constexpr object_category value{object_category::integer_constructible};
1591 };
1592 
1593 /// Assignable from double
1594 template <typename T>
1595 struct classify_object<T,
1596  typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1597  !is_wrapper<T>::value && is_direct_constructible<T, double>::value &&
1598  !is_direct_constructible<T, int>::value>::type> {
1599  static constexpr object_category value{object_category::double_constructible};
1600 };
1601 
1602 /// Tuple type
1603 template <typename T>
1604 struct classify_object<
1605  T,
1606  typename std::enable_if<is_tuple_like<T>::value &&
1607  ((type_count<T>::value >= 2 && !is_wrapper<T>::value) ||
1608  (uncommon_type<T>::value && !is_direct_constructible<T, double>::value &&
1609  !is_direct_constructible<T, int>::value) ||
1610  (uncommon_type<T>::value && type_count<T>::value >= 2))>::type> {
1611  static constexpr object_category value{object_category::tuple_value};
1612  // the condition on this class requires it be like a tuple, but on some compilers (like Xcode) tuples can be
1613  // constructed from just the first element so tuples of <string, int,int> can be constructed from a string, which
1614  // could lead to issues so there are two variants of the condition, the first isolates things with a type size >=2
1615  // mainly to get tuples on Xcode with the exception of wrappers, the second is the main one and just separating out
1616  // those cases that are caught by other object classifications
1617 };
1618 
1619 /// container type
1620 template <typename T> struct classify_object<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1621  static constexpr object_category value{object_category::container_value};
1622 };
1623 
1624 // Type name print
1625 
1626 /// Was going to be based on
1627 /// http://stackoverflow.com/questions/1055452/c-get-name-of-type-in-template
1628 /// But this is cleaner and works better in this case
1629 
1630 template <typename T,
1631  enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> = detail::dummy>
1632 constexpr const char *type_name() {
1633  return "CHAR";
1634 }
1635 
1636 template <typename T,
1637  enable_if_t<classify_object<T>::value == object_category::integral_value ||
1638  classify_object<T>::value == object_category::integer_constructible,
1640 constexpr const char *type_name() {
1641  return "INT";
1642 }
1643 
1644 template <typename T,
1645  enable_if_t<classify_object<T>::value == object_category::unsigned_integral, detail::enabler> = detail::dummy>
1646 constexpr const char *type_name() {
1647  return "UINT";
1648 }
1649 
1650 template <typename T,
1651  enable_if_t<classify_object<T>::value == object_category::floating_point ||
1652  classify_object<T>::value == object_category::number_constructible ||
1653  classify_object<T>::value == object_category::double_constructible,
1655 constexpr const char *type_name() {
1656  return "FLOAT";
1657 }
1658 
1659 /// Print name for enumeration types
1660 template <typename T,
1661  enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> = detail::dummy>
1662 constexpr const char *type_name() {
1663  return "ENUM";
1664 }
1665 
1666 /// Print name for enumeration types
1667 template <typename T,
1668  enable_if_t<classify_object<T>::value == object_category::boolean_value, detail::enabler> = detail::dummy>
1669 constexpr const char *type_name() {
1670  return "BOOLEAN";
1671 }
1672 
1673 /// Print name for enumeration types
1674 template <typename T,
1675  enable_if_t<classify_object<T>::value == object_category::complex_number, detail::enabler> = detail::dummy>
1676 constexpr const char *type_name() {
1677  return "COMPLEX";
1678 }
1679 
1680 /// Print for all other types
1681 template <typename T,
1682  enable_if_t<classify_object<T>::value >= object_category::string_assignable &&
1683  classify_object<T>::value <= object_category::other,
1685 constexpr const char *type_name() {
1686  return "TEXT";
1687 }
1688 /// typename for tuple value
1689 template <typename T,
1690  enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value >= 2,
1692 std::string type_name(); // forward declaration
1693 
1694 /// Generate type name for a wrapper or container value
1695 template <typename T,
1696  enable_if_t<classify_object<T>::value == object_category::container_value ||
1697  classify_object<T>::value == object_category::wrapper_value,
1699 std::string type_name(); // forward declaration
1700 
1701 /// Print name for single element tuple types
1702 template <typename T,
1703  enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value == 1,
1705 inline std::string type_name() {
1707 }
1708 
1709 /// Empty string if the index > tuple size
1710 template <typename T, std::size_t I>
1712  return std::string{};
1713 }
1714 
1715 /// Recursively generate the tuple type name
1716 template <typename T, std::size_t I>
1717 inline typename std::enable_if<(I < type_count_base<T>::value), std::string>::type tuple_name() {
1719  tuple_name<T, I + 1>();
1720  if(str.back() == ',')
1721  str.pop_back();
1722  return str;
1723 }
1724 
1725 /// Print type name for tuples with 2 or more elements
1726 template <typename T,
1727  enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value >= 2,
1728  detail::enabler>>
1730  auto tname = std::string(1, '[') + tuple_name<T, 0>();
1731  tname.push_back(']');
1732  return tname;
1733 }
1734 
1735 /// get the type name for a type that has a value_type member
1736 template <typename T,
1737  enable_if_t<classify_object<T>::value == object_category::container_value ||
1738  classify_object<T>::value == object_category::wrapper_value,
1739  detail::enabler>>
1741  return type_name<typename T::value_type>();
1742 }
1743 
1744 // Lexical cast
1745 
1746 /// Convert to an unsigned integral
1748 bool integral_conversion(const std::string &input, T &output) noexcept {
1749  if(input.empty()) {
1750  return false;
1751  }
1752  char *val = nullptr;
1753  std::uint64_t output_ll = std::strtoull(input.c_str(), &val, 0);
1754  output = static_cast<T>(output_ll);
1755  if(val == (input.c_str() + input.size()) && static_cast<std::uint64_t>(output) == output_ll) {
1756  return true;
1757  }
1758  val = nullptr;
1759  std::int64_t output_sll = std::strtoll(input.c_str(), &val, 0);
1760  if(val == (input.c_str() + input.size())) {
1761  output = (output_sll < 0) ? static_cast<T>(0) : static_cast<T>(output_sll);
1762  return (static_cast<std::int64_t>(output) == output_sll);
1763  }
1764  return false;
1765 }
1766 
1767 /// Convert to a signed integral
1769 bool integral_conversion(const std::string &input, T &output) noexcept {
1770  if(input.empty()) {
1771  return false;
1772  }
1773  char *val = nullptr;
1774  std::int64_t output_ll = std::strtoll(input.c_str(), &val, 0);
1775  output = static_cast<T>(output_ll);
1776  if(val == (input.c_str() + input.size()) && static_cast<std::int64_t>(output) == output_ll) {
1777  return true;
1778  }
1779  if(input == "true") {
1780  // this is to deal with a few oddities with flags and wrapper int types
1781  output = static_cast<T>(1);
1782  return true;
1783  }
1784  return false;
1785 }
1786 
1787 /// Convert a flag into an integer value typically binary flags
1788 inline std::int64_t to_flag_value(std::string val) {
1789  static const std::string trueString("true");
1790  static const std::string falseString("false");
1791  if(val == trueString) {
1792  return 1;
1793  }
1794  if(val == falseString) {
1795  return -1;
1796  }
1797  val = detail::to_lower(val);
1798  std::int64_t ret = 0;
1799  if(val.size() == 1) {
1800  if(val[0] >= '1' && val[0] <= '9') {
1801  return (static_cast<std::int64_t>(val[0]) - '0');
1802  }
1803  switch(val[0]) {
1804  case '0':
1805  case 'f':
1806  case 'n':
1807  case '-':
1808  ret = -1;
1809  break;
1810  case 't':
1811  case 'y':
1812  case '+':
1813  ret = 1;
1814  break;
1815  default:
1816  throw std::invalid_argument("unrecognized character");
1817  }
1818  return ret;
1819  }
1820  if(val == trueString || val == "on" || val == "yes" || val == "enable") {
1821  ret = 1;
1822  } else if(val == falseString || val == "off" || val == "no" || val == "disable") {
1823  ret = -1;
1824  } else {
1825  ret = std::stoll(val);
1826  }
1827  return ret;
1828 }
1829 
1830 /// Integer conversion
1831 template <typename T,
1832  enable_if_t<classify_object<T>::value == object_category::integral_value ||
1833  classify_object<T>::value == object_category::unsigned_integral,
1834  detail::enabler> = detail::dummy>
1835 bool lexical_cast(const std::string &input, T &output) {
1836  return integral_conversion(input, output);
1837 }
1838 
1839 /// char values
1840 template <typename T,
1841  enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> = detail::dummy>
1842 bool lexical_cast(const std::string &input, T &output) {
1843  if(input.size() == 1) {
1844  output = static_cast<T>(input[0]);
1845  return true;
1846  }
1847  return integral_conversion(input, output);
1848 }
1849 
1850 /// Boolean values
1851 template <typename T,
1852  enable_if_t<classify_object<T>::value == object_category::boolean_value, detail::enabler> = detail::dummy>
1853 bool lexical_cast(const std::string &input, T &output) {
1854  try {
1855  auto out = to_flag_value(input);
1856  output = (out > 0);
1857  return true;
1858  } catch(const std::invalid_argument &) {
1859  return false;
1860  } catch(const std::out_of_range &) {
1861  // if the number is out of the range of a 64 bit value then it is still a number and for this purpose is still
1862  // valid all we care about the sign
1863  output = (input[0] != '-');
1864  return true;
1865  }
1866 }
1867 
1868 /// Floats
1869 template <typename T,
1870  enable_if_t<classify_object<T>::value == object_category::floating_point, detail::enabler> = detail::dummy>
1871 bool lexical_cast(const std::string &input, T &output) {
1872  if(input.empty()) {
1873  return false;
1874  }
1875  char *val = nullptr;
1876  auto output_ld = std::strtold(input.c_str(), &val);
1877  output = static_cast<T>(output_ld);
1878  return val == (input.c_str() + input.size());
1879 }
1880 
1881 /// complex
1882 template <typename T,
1883  enable_if_t<classify_object<T>::value == object_category::complex_number, detail::enabler> = detail::dummy>
1884 bool lexical_cast(const std::string &input, T &output) {
1885  using XC = typename wrapped_type<T, double>::type;
1886  XC x{0.0}, y{0.0};
1887  auto str1 = input;
1888  bool worked = false;
1889  auto nloc = str1.find_last_of("+-");
1890  if(nloc != std::string::npos && nloc > 0) {
1891  worked = detail::lexical_cast(str1.substr(0, nloc), x);
1892  str1 = str1.substr(nloc);
1893  if(str1.back() == 'i' || str1.back() == 'j')
1894  str1.pop_back();
1895  worked = worked && detail::lexical_cast(str1, y);
1896  } else {
1897  if(str1.back() == 'i' || str1.back() == 'j') {
1898  str1.pop_back();
1899  worked = detail::lexical_cast(str1, y);
1900  x = XC{0};
1901  } else {
1902  worked = detail::lexical_cast(str1, x);
1903  y = XC{0};
1904  }
1905  }
1906  if(worked) {
1907  output = T{x, y};
1908  return worked;
1909  }
1910  return from_stream(input, output);
1911 }
1912 
1913 /// String and similar direct assignment
1914 template <typename T,
1915  enable_if_t<classify_object<T>::value == object_category::string_assignable, detail::enabler> = detail::dummy>
1916 bool lexical_cast(const std::string &input, T &output) {
1917  output = input;
1918  return true;
1919 }
1920 
1921 /// String and similar constructible and copy assignment
1922 template <
1923  typename T,
1924  enable_if_t<classify_object<T>::value == object_category::string_constructible, detail::enabler> = detail::dummy>
1925 bool lexical_cast(const std::string &input, T &output) {
1926  output = T(input);
1927  return true;
1928 }
1929 
1930 /// Enumerations
1931 template <typename T,
1932  enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> = detail::dummy>
1933 bool lexical_cast(const std::string &input, T &output) {
1935  if(!integral_conversion(input, val)) {
1936  return false;
1937  }
1938  output = static_cast<T>(val);
1939  return true;
1940 }
1941 
1942 /// wrapper types
1943 template <typename T,
1944  enable_if_t<classify_object<T>::value == object_category::wrapper_value &&
1946  detail::enabler> = detail::dummy>
1947 bool lexical_cast(const std::string &input, T &output) {
1948  typename T::value_type val;
1949  if(lexical_cast(input, val)) {
1950  output = val;
1951  return true;
1952  }
1953  return from_stream(input, output);
1954 }
1955 
1956 template <typename T,
1957  enable_if_t<classify_object<T>::value == object_category::wrapper_value &&
1958  !std::is_assignable<T &, typename T::value_type>::value && std::is_assignable<T &, T>::value,
1959  detail::enabler> = detail::dummy>
1960 bool lexical_cast(const std::string &input, T &output) {
1961  typename T::value_type val;
1962  if(lexical_cast(input, val)) {
1963  output = T{val};
1964  return true;
1965  }
1966  return from_stream(input, output);
1967 }
1968 
1969 /// Assignable from double or int
1970 template <
1971  typename T,
1972  enable_if_t<classify_object<T>::value == object_category::number_constructible, detail::enabler> = detail::dummy>
1973 bool lexical_cast(const std::string &input, T &output) {
1974  int val = 0;
1975  if(integral_conversion(input, val)) {
1976  output = T(val);
1977  return true;
1978  }
1979 
1980  double dval = 0.0;
1981  if(lexical_cast(input, dval)) {
1982  output = T{dval};
1983  return true;
1984  }
1985 
1986  return from_stream(input, output);
1987 }
1988 
1989 /// Assignable from int
1990 template <
1991  typename T,
1992  enable_if_t<classify_object<T>::value == object_category::integer_constructible, detail::enabler> = detail::dummy>
1993 bool lexical_cast(const std::string &input, T &output) {
1994  int val = 0;
1995  if(integral_conversion(input, val)) {
1996  output = T(val);
1997  return true;
1998  }
1999  return from_stream(input, output);
2000 }
2001 
2002 /// Assignable from double
2003 template <
2004  typename T,
2005  enable_if_t<classify_object<T>::value == object_category::double_constructible, detail::enabler> = detail::dummy>
2006 bool lexical_cast(const std::string &input, T &output) {
2007  double val = 0.0;
2008  if(lexical_cast(input, val)) {
2009  output = T{val};
2010  return true;
2011  }
2012  return from_stream(input, output);
2013 }
2014 
2015 /// Non-string convertible from an int
2016 template <typename T,
2017  enable_if_t<classify_object<T>::value == object_category::other && std::is_assignable<T &, int>::value,
2018  detail::enabler> = detail::dummy>
2019 bool lexical_cast(const std::string &input, T &output) {
2020  int val = 0;
2021  if(integral_conversion(input, val)) {
2022 #ifdef _MSC_VER
2023 #pragma warning(push)
2024 #pragma warning(disable : 4800)
2025 #endif
2026  // with Atomic<XX> this could produce a warning due to the conversion but if atomic gets here it is an old style
2027  // so will most likely still work
2028  output = val;
2029 #ifdef _MSC_VER
2030 #pragma warning(pop)
2031 #endif
2032  return true;
2033  }
2034  // LCOV_EXCL_START
2035  // This version of cast is only used for odd cases in an older compilers the fail over
2036  // from_stream is tested elsewhere an not relevant for coverage here
2037  return from_stream(input, output);
2038  // LCOV_EXCL_STOP
2039 }
2040 
2041 /// Non-string parsable by a stream
2042 template <typename T,
2043  enable_if_t<classify_object<T>::value == object_category::other && !std::is_assignable<T &, int>::value,
2044  detail::enabler> = detail::dummy>
2045 bool lexical_cast(const std::string &input, T &output) {
2046  static_assert(is_istreamable<T>::value,
2047  "option object type must have a lexical cast overload or streaming input operator(>>) defined, if it "
2048  "is convertible from another type use the add_option<T, XC>(...) with XC being the known type");
2049  return from_stream(input, output);
2050 }
2051 
2052 /// Assign a value through lexical cast operations
2053 /// Strings can be empty so we need to do a little different
2054 template <typename AssignTo,
2055  typename ConvertTo,
2057  (classify_object<AssignTo>::value == object_category::string_assignable ||
2058  classify_object<AssignTo>::value == object_category::string_constructible),
2059  detail::enabler> = detail::dummy>
2060 bool lexical_assign(const std::string &input, AssignTo &output) {
2061  return lexical_cast(input, output);
2062 }
2063 
2064 /// Assign a value through lexical cast operations
2065 template <typename AssignTo,
2066  typename ConvertTo,
2068  classify_object<AssignTo>::value != object_category::string_assignable &&
2069  classify_object<AssignTo>::value != object_category::string_constructible,
2070  detail::enabler> = detail::dummy>
2071 bool lexical_assign(const std::string &input, AssignTo &output) {
2072  if(input.empty()) {
2073  output = AssignTo{};
2074  return true;
2075  }
2076 
2077  return lexical_cast(input, output);
2078 }
2079 
2080 /// Assign a value through lexical cast operations
2081 template <typename AssignTo,
2082  typename ConvertTo,
2084  classify_object<AssignTo>::value == object_category::wrapper_value,
2085  detail::enabler> = detail::dummy>
2086 bool lexical_assign(const std::string &input, AssignTo &output) {
2087  if(input.empty()) {
2088  typename AssignTo::value_type emptyVal{};
2089  output = emptyVal;
2090  return true;
2091  }
2092  return lexical_cast(input, output);
2093 }
2094 
2095 /// Assign a value through lexical cast operations for int compatible values
2096 /// mainly for atomic operations on some compilers
2097 template <typename AssignTo,
2098  typename ConvertTo,
2100  classify_object<AssignTo>::value != object_category::wrapper_value &&
2102  detail::enabler> = detail::dummy>
2103 bool lexical_assign(const std::string &input, AssignTo &output) {
2104  if(input.empty()) {
2105  output = 0;
2106  return true;
2107  }
2108  int val = 0;
2109  if(lexical_cast(input, val)) {
2110  output = val;
2111  return true;
2112  }
2113  return false;
2114 }
2115 
2116 /// Assign a value converted from a string in lexical cast to the output value directly
2117 template <typename AssignTo,
2118  typename ConvertTo,
2120  detail::enabler> = detail::dummy>
2121 bool lexical_assign(const std::string &input, AssignTo &output) {
2122  ConvertTo val{};
2123  bool parse_result = (!input.empty()) ? lexical_cast<ConvertTo>(input, val) : true;
2124  if(parse_result) {
2125  output = val;
2126  }
2127  return parse_result;
2128 }
2129 
2130 /// Assign a value from a lexical cast through constructing a value and move assigning it
2131 template <
2132  typename AssignTo,
2133  typename ConvertTo,
2134  enable_if_t<!std::is_same<AssignTo, ConvertTo>::value && !std::is_assignable<AssignTo &, ConvertTo &>::value &&
2136  detail::enabler> = detail::dummy>
2137 bool lexical_assign(const std::string &input, AssignTo &output) {
2138  ConvertTo val{};
2139  bool parse_result = input.empty() ? true : lexical_cast<ConvertTo>(input, val);
2140  if(parse_result) {
2141  output = AssignTo(val); // use () form of constructor to allow some implicit conversions
2142  }
2143  return parse_result;
2144 }
2145 
2146 /// primary lexical conversion operation, 1 string to 1 type of some kind
2147 template <typename AssignTo,
2148  typename ConvertTo,
2149  enable_if_t<classify_object<ConvertTo>::value <= object_category::other &&
2150  classify_object<AssignTo>::value <= object_category::wrapper_value,
2151  detail::enabler> = detail::dummy>
2152 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2153  return lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2154 }
2155 
2156 /// Lexical conversion if there is only one element but the conversion type is for two, then call a two element
2157 /// constructor
2158 template <typename AssignTo,
2159  typename ConvertTo,
2162  detail::enabler> = detail::dummy>
2163 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2164  // the remove const is to handle pair types coming from a container
2167  bool retval = lexical_assign<decltype(v1), decltype(v1)>(strings[0], v1);
2168  if(strings.size() > 1) {
2169  retval = retval && lexical_assign<decltype(v2), decltype(v2)>(strings[1], v2);
2170  }
2171  if(retval) {
2172  output = AssignTo{v1, v2};
2173  }
2174  return retval;
2175 }
2176 
2177 /// Lexical conversion of a container types of single elements
2178 template <class AssignTo,
2179  class ConvertTo,
2182  detail::enabler> = detail::dummy>
2183 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2184  output.erase(output.begin(), output.end());
2185  if(strings.size() == 1 && strings[0] == "{}") {
2186  return true;
2187  }
2188  bool skip_remaining = false;
2189  if(strings.size() == 2 && strings[0] == "{}" && is_separator(strings[1])) {
2190  skip_remaining = true;
2191  }
2192  for(const auto &elem : strings) {
2193  typename AssignTo::value_type out;
2194  bool retval = lexical_assign<typename AssignTo::value_type, typename ConvertTo::value_type>(elem, out);
2195  if(!retval) {
2196  return false;
2197  }
2198  output.insert(output.end(), std::move(out));
2199  if(skip_remaining) {
2200  break;
2201  }
2202  }
2203  return (!output.empty());
2204 }
2205 
2206 /// Lexical conversion for complex types
2208 bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output) {
2209 
2210  if(strings.size() >= 2 && !strings[1].empty()) {
2211  using XC2 = typename wrapped_type<ConvertTo, double>::type;
2212  XC2 x{0.0}, y{0.0};
2213  auto str1 = strings[1];
2214  if(str1.back() == 'i' || str1.back() == 'j') {
2215  str1.pop_back();
2216  }
2217  auto worked = detail::lexical_cast(strings[0], x) && detail::lexical_cast(str1, y);
2218  if(worked) {
2219  output = ConvertTo{x, y};
2220  }
2221  return worked;
2222  }
2223  return lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2224 }
2225 
2226 /// Conversion to a vector type using a particular single type as the conversion type
2227 template <class AssignTo,
2228  class ConvertTo,
2230  (type_count<ConvertTo>::value == 1),
2231  detail::enabler> = detail::dummy>
2232 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2233  bool retval = true;
2234  output.clear();
2235  output.reserve(strings.size());
2236  for(const auto &elem : strings) {
2237 
2238  output.emplace_back();
2239  retval = retval && lexical_assign<typename AssignTo::value_type, ConvertTo>(elem, output.back());
2240  }
2241  return (!output.empty()) && retval;
2242 }
2243 
2244 // forward declaration
2245 
2246 /// Lexical conversion of a container types with conversion type of two elements
2247 template <class AssignTo,
2248  class ConvertTo,
2251  detail::enabler> = detail::dummy>
2252 bool lexical_conversion(std::vector<std::string> strings, AssignTo &output);
2253 
2254 /// Lexical conversion of a vector types with type_size >2 forward declaration
2255 template <class AssignTo,
2256  class ConvertTo,
2258  type_count_base<ConvertTo>::value != 2 &&
2259  ((type_count<ConvertTo>::value > 2) ||
2260  (type_count<ConvertTo>::value > type_count_base<ConvertTo>::value)),
2261  detail::enabler> = detail::dummy>
2262 bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output);
2263 
2264 /// Conversion for tuples
2265 template <class AssignTo,
2266  class ConvertTo,
2268  (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
2269  type_count<ConvertTo>::value > 2),
2270  detail::enabler> = detail::dummy>
2271 bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output); // forward declaration
2272 
2273 /// Conversion for operations where the assigned type is some class but the conversion is a mutable container or large
2274 /// tuple
2275 template <typename AssignTo,
2276  typename ConvertTo,
2278  classify_object<ConvertTo>::value != object_category::wrapper_value &&
2279  (is_mutable_container<ConvertTo>::value || type_count<ConvertTo>::value > 2),
2280  detail::enabler> = detail::dummy>
2281 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2282 
2283  if(strings.size() > 1 || (!strings.empty() && !(strings.front().empty()))) {
2284  ConvertTo val;
2285  auto retval = lexical_conversion<ConvertTo, ConvertTo>(strings, val);
2286  output = AssignTo{val};
2287  return retval;
2288  }
2289  output = AssignTo{};
2290  return true;
2291 }
2292 
2293 /// function template for converting tuples if the static Index is greater than the tuple size
2294 template <class AssignTo, class ConvertTo, std::size_t I>
2295 inline typename std::enable_if<(I >= type_count_base<AssignTo>::value), bool>::type
2296 tuple_conversion(const std::vector<std::string> &, AssignTo &) {
2297  return true;
2298 }
2299 
2300 /// Conversion of a tuple element where the type size ==1 and not a mutable container
2301 template <class AssignTo, class ConvertTo>
2302 inline typename std::enable_if<!is_mutable_container<ConvertTo>::value && type_count<ConvertTo>::value == 1, bool>::type
2303 tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2304  auto retval = lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2305  strings.erase(strings.begin());
2306  return retval;
2307 }
2308 
2309 /// Conversion of a tuple element where the type size !=1 but the size is fixed and not a mutable container
2310 template <class AssignTo, class ConvertTo>
2311 inline typename std::enable_if<!is_mutable_container<ConvertTo>::value && (type_count<ConvertTo>::value > 1) &&
2312  type_count<ConvertTo>::value == type_count_min<ConvertTo>::value,
2313  bool>::type
2314 tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2315  auto retval = lexical_conversion<AssignTo, ConvertTo>(strings, output);
2316  strings.erase(strings.begin(), strings.begin() + type_count<ConvertTo>::value);
2317  return retval;
2318 }
2319 
2320 /// Conversion of a tuple element where the type is a mutable container or a type with different min and max type sizes
2321 template <class AssignTo, class ConvertTo>
2323  type_count<ConvertTo>::value != type_count_min<ConvertTo>::value,
2324  bool>::type
2325 tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2326 
2328  const std::size_t mx_count{subtype_count<ConvertTo>::value};
2329  const std::size_t mx{(std::max)(mx_count, strings.size())};
2330 
2331  while(index < mx) {
2332  if(is_separator(strings[index])) {
2333  break;
2334  }
2335  ++index;
2336  }
2337  bool retval = lexical_conversion<AssignTo, ConvertTo>(
2338  std::vector<std::string>(strings.begin(), strings.begin() + static_cast<std::ptrdiff_t>(index)), output);
2339  strings.erase(strings.begin(), strings.begin() + static_cast<std::ptrdiff_t>(index) + 1);
2340  return retval;
2341 }
2342 
2343 /// Tuple conversion operation
2344 template <class AssignTo, class ConvertTo, std::size_t I>
2346 tuple_conversion(std::vector<std::string> strings, AssignTo &output) {
2347  bool retval = true;
2348  using ConvertToElement = typename std::
2350  if(!strings.empty()) {
2351  retval = retval && tuple_type_conversion<typename std::tuple_element<I, AssignTo>::type, ConvertToElement>(
2352  strings, std::get<I>(output));
2353  }
2354  retval = retval && tuple_conversion<AssignTo, ConvertTo, I + 1>(std::move(strings), output);
2355  return retval;
2356 }
2357 
2358 /// Lexical conversion of a container types with tuple elements of size 2
2359 template <class AssignTo,
2360  class ConvertTo,
2362  type_count_base<ConvertTo>::value == 2,
2363  detail::enabler>>
2364 bool lexical_conversion(std::vector<std::string> strings, AssignTo &output) {
2365  output.clear();
2366  while(!strings.empty()) {
2367 
2370  bool retval = tuple_type_conversion<decltype(v1), decltype(v1)>(strings, v1);
2371  if(!strings.empty()) {
2372  retval = retval && tuple_type_conversion<decltype(v2), decltype(v2)>(strings, v2);
2373  }
2374  if(retval) {
2375  output.insert(output.end(), typename AssignTo::value_type{v1, v2});
2376  } else {
2377  return false;
2378  }
2379  }
2380  return (!output.empty());
2381 }
2382 
2383 /// lexical conversion of tuples with type count>2 or tuples of types of some element with a type size>=2
2384 template <class AssignTo,
2385  class ConvertTo,
2387  (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
2388  type_count<ConvertTo>::value > 2),
2389  detail::enabler>>
2390 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2391  static_assert(
2392  !is_tuple_like<ConvertTo>::value || type_count_base<AssignTo>::value == type_count_base<ConvertTo>::value,
2393  "if the conversion type is defined as a tuple it must be the same size as the type you are converting to");
2394  return tuple_conversion<AssignTo, ConvertTo, 0>(strings, output);
2395 }
2396 
2397 /// Lexical conversion of a vector types for everything but tuples of two elements and types of size 1
2398 template <class AssignTo,
2399  class ConvertTo,
2401  type_count_base<ConvertTo>::value != 2 &&
2402  ((type_count<ConvertTo>::value > 2) ||
2403  (type_count<ConvertTo>::value > type_count_base<ConvertTo>::value)),
2404  detail::enabler>>
2405 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2406  bool retval = true;
2407  output.clear();
2408  std::vector<std::string> temp;
2409  std::size_t ii{0};
2410  std::size_t icount{0};
2411  std::size_t xcm{type_count<ConvertTo>::value};
2412  auto ii_max = strings.size();
2413  while(ii < ii_max) {
2414  temp.push_back(strings[ii]);
2415  ++ii;
2416  ++icount;
2417  if(icount == xcm || is_separator(temp.back()) || ii == ii_max) {
2418  if(static_cast<int>(xcm) > type_count_min<ConvertTo>::value && is_separator(temp.back())) {
2419  temp.pop_back();
2420  }
2421  typename AssignTo::value_type temp_out;
2422  retval = retval &&
2423  lexical_conversion<typename AssignTo::value_type, typename ConvertTo::value_type>(temp, temp_out);
2424  temp.clear();
2425  if(!retval) {
2426  return false;
2427  }
2428  output.insert(output.end(), std::move(temp_out));
2429  icount = 0;
2430  }
2431  }
2432  return retval;
2433 }
2434 
2435 /// conversion for wrapper types
2436 template <typename AssignTo,
2437  class ConvertTo,
2438  enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
2440  detail::enabler> = detail::dummy>
2441 bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output) {
2442  if(strings.empty() || strings.front().empty()) {
2443  output = ConvertTo{};
2444  return true;
2445  }
2446  typename ConvertTo::value_type val;
2447  if(lexical_conversion<typename ConvertTo::value_type, typename ConvertTo::value_type>(strings, val)) {
2448  output = ConvertTo{val};
2449  return true;
2450  }
2451  return false;
2452 }
2453 
2454 /// conversion for wrapper types
2455 template <typename AssignTo,
2456  class ConvertTo,
2457  enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
2459  detail::enabler> = detail::dummy>
2460 bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output) {
2461  using ConvertType = typename ConvertTo::value_type;
2462  if(strings.empty() || strings.front().empty()) {
2463  output = ConvertType{};
2464  return true;
2465  }
2466  ConvertType val;
2467  if(lexical_conversion<typename ConvertTo::value_type, typename ConvertTo::value_type>(strings, val)) {
2468  output = val;
2469  return true;
2470  }
2471  return false;
2472 }
2473 
2474 /// Sum a vector of strings
2475 inline std::string sum_string_vector(const std::vector<std::string> &values) {
2476  double val{0.0};
2477  bool fail{false};
2478  std::string output;
2479  for(const auto &arg : values) {
2480  double tv{0.0};
2481  auto comp = detail::lexical_cast<double>(arg, tv);
2482  if(!comp) {
2483  try {
2484  tv = static_cast<double>(detail::to_flag_value(arg));
2485  } catch(const std::exception &) {
2486  fail = true;
2487  break;
2488  }
2489  }
2490  val += tv;
2491  }
2492  if(fail) {
2493  for(const auto &arg : values) {
2494  output.append(arg);
2495  }
2496  } else {
2497  if(val <= static_cast<double>((std::numeric_limits<std::int64_t>::min)()) ||
2498  val >= static_cast<double>((std::numeric_limits<std::int64_t>::max)()) ||
2499  // NOLINTNEXTLINE(clang-diagnostic-float-equal,bugprone-narrowing-conversions)
2500  val == static_cast<std::int64_t>(val)) {
2501  output = detail::value_string(static_cast<int64_t>(val));
2502  } else {
2503  output = detail::value_string(val);
2504  }
2505  }
2506  return output;
2507 }
2508 
2509 } // namespace detail
2510 
2511 
2512 
2513 namespace detail {
2514 
2515 // Returns false if not a short option. Otherwise, sets opt name and rest and returns true
2517 
2518 // Returns false if not a long option. Otherwise, sets opt name and other side of = and returns true
2519 CLI11_INLINE bool split_long(const std::string &current, std::string &name, std::string &value);
2520 
2521 // Returns false if not a windows style option. Otherwise, sets opt name and value and returns true
2523 
2524 // Splits a string into multiple long and short names
2525 CLI11_INLINE std::vector<std::string> split_names(std::string current);
2526 
2527 /// extract default flag values either {def} or starting with a !
2528 CLI11_INLINE std::vector<std::pair<std::string, std::string>> get_default_flag_values(const std::string &str);
2529 
2530 /// Get a vector of short names, one of long names, and a single name
2531 CLI11_INLINE std::tuple<std::vector<std::string>, std::vector<std::string>, std::string>
2532 get_names(const std::vector<std::string> &input);
2533 
2534 } // namespace detail
2535 
2536 
2537 
2538 namespace detail {
2539 
2541  if(current.size() > 1 && current[0] == '-' && valid_first_char(current[1])) {
2542  name = current.substr(1, 1);
2543  rest = current.substr(2);
2544  return true;
2545  }
2546  return false;
2547 }
2548 
2550  if(current.size() > 2 && current.substr(0, 2) == "--" && valid_first_char(current[2])) {
2551  auto loc = current.find_first_of('=');
2552  if(loc != std::string::npos) {
2553  name = current.substr(2, loc - 2);
2554  value = current.substr(loc + 1);
2555  } else {
2556  name = current.substr(2);
2557  value = "";
2558  }
2559  return true;
2560  }
2561  return false;
2562 }
2563 
2565  if(current.size() > 1 && current[0] == '/' && valid_first_char(current[1])) {
2566  auto loc = current.find_first_of(':');
2567  if(loc != std::string::npos) {
2568  name = current.substr(1, loc - 1);
2569  value = current.substr(loc + 1);
2570  } else {
2571  name = current.substr(1);
2572  value = "";
2573  }
2574  return true;
2575  }
2576  return false;
2577 }
2578 
2579 CLI11_INLINE std::vector<std::string> split_names(std::string current) {
2580  std::vector<std::string> output;
2581  std::size_t val = 0;
2582  while((val = current.find(',')) != std::string::npos) {
2583  output.push_back(trim_copy(current.substr(0, val)));
2584  current = current.substr(val + 1);
2585  }
2586  output.push_back(trim_copy(current));
2587  return output;
2588 }
2589 
2590 CLI11_INLINE std::vector<std::pair<std::string, std::string>> get_default_flag_values(const std::string &str) {
2591  std::vector<std::string> flags = split_names(str);
2592  flags.erase(std::remove_if(flags.begin(),
2593  flags.end(),
2594  [](const std::string &name) {
2595  return ((name.empty()) || (!(((name.find_first_of('{') != std::string::npos) &&
2596  (name.back() == '}')) ||
2597  (name[0] == '!'))));
2598  }),
2599  flags.end());
2600  std::vector<std::pair<std::string, std::string>> output;
2601  output.reserve(flags.size());
2602  for(auto &flag : flags) {
2603  auto def_start = flag.find_first_of('{');
2604  std::string defval = "false";
2605  if((def_start != std::string::npos) && (flag.back() == '}')) {
2606  defval = flag.substr(def_start + 1);
2607  defval.pop_back();
2608  flag.erase(def_start, std::string::npos); // NOLINT(readability-suspicious-call-argument)
2609  }
2610  flag.erase(0, flag.find_first_not_of("-!"));
2611  output.emplace_back(flag, defval);
2612  }
2613  return output;
2614 }
2615 
2616 CLI11_INLINE std::tuple<std::vector<std::string>, std::vector<std::string>, std::string>
2617 get_names(const std::vector<std::string> &input) {
2618 
2619  std::vector<std::string> short_names;
2620  std::vector<std::string> long_names;
2621  std::string pos_name;
2622 
2623  for(std::string name : input) {
2624  if(name.length() == 0) {
2625  continue;
2626  }
2627  if(name.length() > 1 && name[0] == '-' && name[1] != '-') {
2628  if(name.length() == 2 && valid_first_char(name[1]))
2629  short_names.emplace_back(1, name[1]);
2630  else
2631  throw BadNameString::OneCharName(name);
2632  } else if(name.length() > 2 && name.substr(0, 2) == "--") {
2633  name = name.substr(2);
2634  if(valid_name_string(name))
2635  long_names.push_back(name);
2636  else
2637  throw BadNameString::BadLongName(name);
2638  } else if(name == "-" || name == "--") {
2639  throw BadNameString::DashesOnly(name);
2640  } else {
2641  if(pos_name.length() > 0)
2642  throw BadNameString::MultiPositionalNames(name);
2643  pos_name = name;
2644  }
2645  }
2646 
2647  return std::make_tuple(short_names, long_names, pos_name);
2648 }
2649 
2650 } // namespace detail
2651 
2652 
2653 
2654 class App;
2655 
2656 /// Holds values to load into Options
2657 struct ConfigItem {
2658  /// This is the list of parents
2659  std::vector<std::string> parents{};
2660 
2661  /// This is the name
2663 
2664  /// Listing of inputs
2665  std::vector<std::string> inputs{};
2666 
2667  /// The list of parents and name joined by "."
2669  std::vector<std::string> tmp = parents;
2670  tmp.emplace_back(name);
2671  return detail::join(tmp, ".");
2672  }
2673 };
2674 
2675 /// This class provides a converter for configuration files.
2676 class Config {
2677  protected:
2678  std::vector<ConfigItem> items{};
2679 
2680  public:
2681  /// Convert an app into a configuration
2682  virtual std::string to_config(const App *, bool, bool, std::string) const = 0;
2683 
2684  /// Convert a configuration into an app
2685  virtual std::vector<ConfigItem> from_config(std::istream &) const = 0;
2686 
2687  /// Get a flag value
2688  CLI11_NODISCARD virtual std::string to_flag(const ConfigItem &item) const {
2689  if(item.inputs.size() == 1) {
2690  return item.inputs.at(0);
2691  }
2692  if(item.inputs.empty()) {
2693  return "{}";
2694  }
2695  throw ConversionError::TooManyInputsFlag(item.fullname()); // LCOV_EXCL_LINE
2696  }
2697 
2698  /// Parse a config file, throw an error (ParseError:ConfigParseError or FileError) on failure
2699  CLI11_NODISCARD std::vector<ConfigItem> from_file(const std::string &name) const {
2700  std::ifstream input{name};
2701  if(!input.good())
2702  throw FileError::Missing(name);
2703 
2704  return from_config(input);
2705  }
2706 
2707  /// Virtual destructor
2708  virtual ~Config() = default;
2709 };
2710 
2711 /// This converter works with INI/TOML files; to write INI files use ConfigINI
2712 class ConfigBase : public Config {
2713  protected:
2714  /// the character used for comments
2715  char commentChar = '#';
2716  /// the character used to start an array '\0' is a default to not use
2717  char arrayStart = '[';
2718  /// the character used to end an array '\0' is a default to not use
2719  char arrayEnd = ']';
2720  /// the character used to separate elements in an array
2721  char arraySeparator = ',';
2722  /// the character used separate the name from the value
2723  char valueDelimiter = '=';
2724  /// the character to use around strings
2725  char stringQuote = '"';
2726  /// the character to use around single characters
2727  char characterQuote = '\'';
2728  /// the maximum number of layers to allow
2729  uint8_t maximumLayers{255};
2730  /// the separator used to separator parent layers
2731  char parentSeparatorChar{'.'};
2732  /// Specify the configuration index to use for arrayed sections
2733  int16_t configIndex{-1};
2734  /// Specify the configuration section that should be used
2735  std::string configSection{};
2736 
2737  public:
2738  std::string
2739  to_config(const App * /*app*/, bool default_also, bool write_description, std::string prefix) const override;
2740 
2741  std::vector<ConfigItem> from_config(std::istream &input) const override;
2742  /// Specify the configuration for comment characters
2743  ConfigBase *comment(char cchar) {
2744  commentChar = cchar;
2745  return this;
2746  }
2747  /// Specify the start and end characters for an array
2748  ConfigBase *arrayBounds(char aStart, char aEnd) {
2749  arrayStart = aStart;
2750  arrayEnd = aEnd;
2751  return this;
2752  }
2753  /// Specify the delimiter character for an array
2755  arraySeparator = aSep;
2756  return this;
2757  }
2758  /// Specify the delimiter between a name and value
2760  valueDelimiter = vSep;
2761  return this;
2762  }
2763  /// Specify the quote characters used around strings and characters
2764  ConfigBase *quoteCharacter(char qString, char qChar) {
2765  stringQuote = qString;
2766  characterQuote = qChar;
2767  return this;
2768  }
2769  /// Specify the maximum number of parents
2770  ConfigBase *maxLayers(uint8_t layers) {
2771  maximumLayers = layers;
2772  return this;
2773  }
2774  /// Specify the separator to use for parent layers
2776  parentSeparatorChar = sep;
2777  return this;
2778  }
2779  /// get a reference to the configuration section
2780  std::string &sectionRef() { return configSection; }
2781  /// get the section
2782  CLI11_NODISCARD const std::string &section() const { return configSection; }
2783  /// specify a particular section of the configuration file to use
2784  ConfigBase *section(const std::string &sectionName) {
2785  configSection = sectionName;
2786  return this;
2787  }
2788 
2789  /// get a reference to the configuration index
2790  int16_t &indexRef() { return configIndex; }
2791  /// get the section index
2792  CLI11_NODISCARD int16_t index() const { return configIndex; }
2793  /// specify a particular index in the section to use (-1) for all sections to use
2794  ConfigBase *index(int16_t sectionIndex) {
2795  configIndex = sectionIndex;
2796  return this;
2797  }
2798 };
2799 
2800 /// the default Config is the TOML file format
2802 
2803 /// ConfigINI generates a "standard" INI compliant output
2804 class ConfigINI : public ConfigTOML {
2805 
2806  public:
2808  commentChar = ';';
2809  arrayStart = '\0';
2810  arrayEnd = '\0';
2811  arraySeparator = ' ';
2812  valueDelimiter = '=';
2813  }
2814 };
2815 
2816 
2817 
2818 class Option;
2819 
2820 /// @defgroup validator_group Validators
2821 
2822 /// @brief Some validators that are provided
2823 ///
2824 /// These are simple `std::string(const std::string&)` validators that are useful. They return
2825 /// a string if the validation fails. A custom struct is provided, as well, with the same user
2826 /// semantics, but with the ability to provide a new type name.
2827 /// @{
2828 
2829 ///
2830 class Validator {
2831  protected:
2832  /// This is the description function, if empty the description_ will be used
2833  std::function<std::string()> desc_function_{[]() { return std::string{}; }};
2834 
2835  /// This is the base function that is to be called.
2836  /// Returns a string error message if validation fails.
2837  std::function<std::string(std::string &)> func_{[](std::string &) { return std::string{}; }};
2838  /// The name for search purposes of the Validator
2839  std::string name_{};
2840  /// A Validator will only apply to an indexed value (-1 is all elements)
2841  int application_index_ = -1;
2842  /// Enable for Validator to allow it to be disabled if need be
2843  bool active_{true};
2844  /// specify that a validator should not modify the input
2845  bool non_modifying_{false};
2846 
2847  Validator(std::string validator_desc, std::function<std::string(std::string &)> func)
2848  : desc_function_([validator_desc]() { return validator_desc; }), func_(std::move(func)) {}
2849 
2850  public:
2851  Validator() = default;
2852  /// Construct a Validator with just the description string
2853  explicit Validator(std::string validator_desc) : desc_function_([validator_desc]() { return validator_desc; }) {}
2854  /// Construct Validator from basic information
2855  Validator(std::function<std::string(std::string &)> op, std::string validator_desc, std::string validator_name = "")
2856  : desc_function_([validator_desc]() { return validator_desc; }), func_(std::move(op)),
2857  name_(std::move(validator_name)) {}
2858  /// Set the Validator operation function
2859  Validator &operation(std::function<std::string(std::string &)> op) {
2860  func_ = std::move(op);
2861  return *this;
2862  }
2863  /// This is the required operator for a Validator - provided to help
2864  /// users (CLI11 uses the member `func` directly)
2865  std::string operator()(std::string &str) const;
2866 
2867  /// This is the required operator for a Validator - provided to help
2868  /// users (CLI11 uses the member `func` directly)
2869  std::string operator()(const std::string &str) const {
2870  std::string value = str;
2871  return (active_) ? func_(value) : std::string{};
2872  }
2873 
2874  /// Specify the type string
2875  Validator &description(std::string validator_desc) {
2876  desc_function_ = [validator_desc]() { return validator_desc; };
2877  return *this;
2878  }
2879  /// Specify the type string
2880  CLI11_NODISCARD Validator description(std::string validator_desc) const;
2881 
2882  /// Generate type description information for the Validator
2884  if(active_) {
2885  return desc_function_();
2886  }
2887  return std::string{};
2888  }
2889  /// Specify the type string
2890  Validator &name(std::string validator_name) {
2891  name_ = std::move(validator_name);
2892  return *this;
2893  }
2894  /// Specify the type string
2895  CLI11_NODISCARD Validator name(std::string validator_name) const {
2896  Validator newval(*this);
2897  newval.name_ = std::move(validator_name);
2898  return newval;
2899  }
2900  /// Get the name of the Validator
2901  CLI11_NODISCARD const std::string &get_name() const { return name_; }
2902  /// Specify whether the Validator is active or not
2903  Validator &active(bool active_val = true) {
2904  active_ = active_val;
2905  return *this;
2906  }
2907  /// Specify whether the Validator is active or not
2908  CLI11_NODISCARD Validator active(bool active_val = true) const {
2909  Validator newval(*this);
2910  newval.active_ = active_val;
2911  return newval;
2912  }
2913 
2914  /// Specify whether the Validator can be modifying or not
2915  Validator &non_modifying(bool no_modify = true) {
2916  non_modifying_ = no_modify;
2917  return *this;
2918  }
2919  /// Specify the application index of a validator
2920  Validator &application_index(int app_index) {
2921  application_index_ = app_index;
2922  return *this;
2923  }
2924  /// Specify the application index of a validator
2926  Validator newval(*this);
2927  newval.application_index_ = app_index;
2928  return newval;
2929  }
2930  /// Get the current value of the application index
2931  CLI11_NODISCARD int get_application_index() const { return application_index_; }
2932  /// Get a boolean if the validator is active
2933  CLI11_NODISCARD bool get_active() const { return active_; }
2934 
2935  /// Get a boolean if the validator is allowed to modify the input returns true if it can modify the input
2936  CLI11_NODISCARD bool get_modifying() const { return !non_modifying_; }
2937 
2938  /// Combining validators is a new validator. Type comes from left validator if function, otherwise only set if the
2939  /// same.
2940  Validator operator&(const Validator &other) const;
2941 
2942  /// Combining validators is a new validator. Type comes from left validator if function, otherwise only set if the
2943  /// same.
2944  Validator operator|(const Validator &other) const;
2945 
2946  /// Create a validator that fails when a given validator succeeds
2947  Validator operator!() const;
2948 
2949  private:
2950  void _merge_description(const Validator &val1, const Validator &val2, const std::string &merger);
2951 };
2952 
2953 /// Class wrapping some of the accessors of Validator
2954 class CustomValidator : public Validator {
2955  public:
2956 };
2957 // The implementation of the built in validators is using the Validator class;
2958 // the user is only expected to use the const (static) versions (since there's no setup).
2959 // Therefore, this is in detail.
2960 namespace detail {
2961 
2962 /// CLI enumeration of different file types
2964 
2965 /// get the type of the path from a file name
2966 CLI11_INLINE path_type check_path(const char *file) noexcept;
2967 
2968 /// Check for an existing file (returns error message if check fails)
2970  public:
2972 };
2973 
2974 /// Check for an existing directory (returns error message if check fails)
2976  public:
2978 };
2979 
2980 /// Check for an existing path
2982  public:
2984 };
2985 
2986 /// Check for an non-existing path
2988  public:
2990 };
2991 
2992 /// Validate the given string is a legal ipv4 address
2993 class IPV4Validator : public Validator {
2994  public:
2995  IPV4Validator();
2996 };
2997 
2998 } // namespace detail
2999 
3000 // Static is not needed here, because global const implies static.
3001 
3002 /// Check for existing file (returns error message if check fails)
3004 
3005 /// Check for an existing directory (returns error message if check fails)
3007 
3008 /// Check for an existing path
3010 
3011 /// Check for an non-existing path
3013 
3014 /// Check for an IP4 address
3016 
3017 /// Validate the input as a particular type
3018 template <typename DesiredType> class TypeValidator : public Validator {
3019  public:
3020  explicit TypeValidator(const std::string &validator_name)
3021  : Validator(validator_name, [](std::string &input_string) {
3022  auto val = DesiredType();
3023  if(!detail::lexical_cast(input_string, val)) {
3024  return std::string("Failed parsing ") + input_string + " as a " + detail::type_name<DesiredType>();
3025  }
3026  return std::string();
3027  }) {}
3028  TypeValidator() : TypeValidator(detail::type_name<DesiredType>()) {}
3029 };
3030 
3031 /// Check for a number
3032 const TypeValidator<double> Number("NUMBER");
3033 
3034 /// Modify a path if the file is a particular default location, can be used as Check or transform
3035 /// with the error return optionally disabled
3037  public:
3038  explicit FileOnDefaultPath(std::string default_path, bool enableErrorReturn = true);
3039 };
3040 
3041 /// Produce a range (factory). Min and max are inclusive.
3042 class Range : public Validator {
3043  public:
3044  /// This produces a range with min and max inclusive.
3045  ///
3046  /// Note that the constructor is templated, but the struct is not, so C++17 is not
3047  /// needed to provide nice syntax for Range(a,b).
3048  template <typename T>
3049  Range(T min_val, T max_val, const std::string &validator_name = std::string{}) : Validator(validator_name) {
3050  if(validator_name.empty()) {
3051  std::stringstream out;
3052  out << detail::type_name<T>() << " in [" << min_val << " - " << max_val << "]";
3053  description(out.str());
3054  }
3055 
3056  func_ = [min_val, max_val](std::string &input) {
3057  T val;
3058  bool converted = detail::lexical_cast(input, val);
3059  if((!converted) || (val < min_val || val > max_val)) {
3060  std::stringstream out;
3061  out << "Value " << input << " not in range [";
3062  out << min_val << " - " << max_val << "]";
3063  return out.str();
3064  }
3065  return std::string{};
3066  };
3067  }
3068 
3069  /// Range of one value is 0 to value
3070  template <typename T>
3071  explicit Range(T max_val, const std::string &validator_name = std::string{})
3072  : Range(static_cast<T>(0), max_val, validator_name) {}
3073 };
3074 
3075 /// Check for a non negative number
3076 const Range NonNegativeNumber((std::numeric_limits<double>::max)(), "NONNEGATIVE");
3077 
3078 /// Check for a positive valued number (val>0.0), <double>::min here is the smallest positive number
3080 
3081 /// Produce a bounded range (factory). Min and max are inclusive.
3082 class Bound : public Validator {
3083  public:
3084  /// This bounds a value with min and max inclusive.
3085  ///
3086  /// Note that the constructor is templated, but the struct is not, so C++17 is not
3087  /// needed to provide nice syntax for Range(a,b).
3088  template <typename T> Bound(T min_val, T max_val) {
3089  std::stringstream out;
3090  out << detail::type_name<T>() << " bounded to [" << min_val << " - " << max_val << "]";
3091  description(out.str());
3092 
3093  func_ = [min_val, max_val](std::string &input) {
3094  T val;
3095  bool converted = detail::lexical_cast(input, val);
3096  if(!converted) {
3097  return std::string("Value ") + input + " could not be converted";
3098  }
3099  if(val < min_val)
3100  input = detail::to_string(min_val);
3101  else if(val > max_val)
3102  input = detail::to_string(max_val);
3103 
3104  return std::string{};
3105  };
3106  }
3107 
3108  /// Range of one value is 0 to value
3109  template <typename T> explicit Bound(T max_val) : Bound(static_cast<T>(0), max_val) {}
3110 };
3111 
3112 namespace detail {
3113 template <typename T,
3115 auto smart_deref(T value) -> decltype(*value) {
3116  return *value;
3117 }
3118 
3119 template <
3120  typename T,
3123  return value;
3124 }
3125 /// Generate a string representation of a set
3126 template <typename T> std::string generate_set(const T &set) {
3127  using element_t = typename detail::element_type<T>::type;
3128  using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
3129  std::string out(1, '{');
3130  out.append(detail::join(
3131  detail::smart_deref(set),
3132  [](const iteration_type_t &v) { return detail::pair_adaptor<element_t>::first(v); },
3133  ","));
3134  out.push_back('}');
3135  return out;
3136 }
3137 
3138 /// Generate a string representation of a map
3139 template <typename T> std::string generate_map(const T &map, bool key_only = false) {
3140  using element_t = typename detail::element_type<T>::type;
3141  using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
3142  std::string out(1, '{');
3143  out.append(detail::join(
3144  detail::smart_deref(map),
3145  [key_only](const iteration_type_t &v) {
3147 
3148  if(!key_only) {
3149  res.append("->");
3151  }
3152  return res;
3153  },
3154  ","));
3155  out.push_back('}');
3156  return out;
3157 }
3158 
3159 template <typename C, typename V> struct has_find {
3160  template <typename CC, typename VV>
3161  static auto test(int) -> decltype(std::declval<CC>().find(std::declval<VV>()), std::true_type());
3162  template <typename, typename> static auto test(...) -> decltype(std::false_type());
3163 
3164  static const auto value = decltype(test<C, V>(0))::value;
3165  using type = std::integral_constant<bool, value>;
3166 };
3167 
3168 /// A search function
3170 auto search(const T &set, const V &val) -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
3171  using element_t = typename detail::element_type<T>::type;
3172  auto &setref = detail::smart_deref(set);
3173  auto it = std::find_if(std::begin(setref), std::end(setref), [&val](decltype(*std::begin(setref)) v) {
3174  return (detail::pair_adaptor<element_t>::first(v) == val);
3175  });
3176  return {(it != std::end(setref)), it};
3177 }
3178 
3179 /// A search function that uses the built in find function
3181 auto search(const T &set, const V &val) -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
3182  auto &setref = detail::smart_deref(set);
3183  auto it = setref.find(val);
3184  return {(it != std::end(setref)), it};
3185 }
3186 
3187 /// A search function with a filter function
3188 template <typename T, typename V>
3189 auto search(const T &set, const V &val, const std::function<V(V)> &filter_function)
3190  -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
3191  using element_t = typename detail::element_type<T>::type;
3192  // do the potentially faster first search
3193  auto res = search(set, val);
3194  if((res.first) || (!(filter_function))) {
3195  return res;
3196  }
3197  // if we haven't found it do the longer linear search with all the element translations
3198  auto &setref = detail::smart_deref(set);
3199  auto it = std::find_if(std::begin(setref), std::end(setref), [&](decltype(*std::begin(setref)) v) {
3201  a = filter_function(a);
3202  return (a == val);
3203  });
3204  return {(it != std::end(setref)), it};
3205 }
3206 
3207 // the following suggestion was made by Nikita Ofitserov(@himikof)
3208 // done in templates to prevent compiler warnings on negation of unsigned numbers
3209 
3210 /// Do a check for overflow on signed numbers
3211 template <typename T>
3212 inline typename std::enable_if<std::is_signed<T>::value, T>::type overflowCheck(const T &a, const T &b) {
3213  if((a > 0) == (b > 0)) {
3214  return ((std::numeric_limits<T>::max)() / (std::abs)(a) < (std::abs)(b));
3215  }
3216  return ((std::numeric_limits<T>::min)() / (std::abs)(a) > -(std::abs)(b));
3217 }
3218 /// Do a check for overflow on unsigned numbers
3219 template <typename T>
3220 inline typename std::enable_if<!std::is_signed<T>::value, T>::type overflowCheck(const T &a, const T &b) {
3221  return ((std::numeric_limits<T>::max)() / a < b);
3222 }
3223 
3224 /// Performs a *= b; if it doesn't cause integer overflow. Returns false otherwise.
3225 template <typename T> typename std::enable_if<std::is_integral<T>::value, bool>::type checked_multiply(T &a, T b) {
3226  if(a == 0 || b == 0 || a == 1 || b == 1) {
3227  a *= b;
3228  return true;
3229  }
3230  if(a == (std::numeric_limits<T>::min)() || b == (std::numeric_limits<T>::min)()) {
3231  return false;
3232  }
3233  if(overflowCheck(a, b)) {
3234  return false;
3235  }
3236  a *= b;
3237  return true;
3238 }
3239 
3240 /// Performs a *= b; if it doesn't equal infinity. Returns false otherwise.
3241 template <typename T>
3243  T c = a * b;
3244  if(std::isinf(c) && !std::isinf(a) && !std::isinf(b)) {
3245  return false;
3246  }
3247  a = c;
3248  return true;
3249 }
3250 
3251 } // namespace detail
3252 /// Verify items are in a set
3253 class IsMember : public Validator {
3254  public:
3255  using filter_fn_t = std::function<std::string(std::string)>;
3256 
3257  /// This allows in-place construction using an initializer list
3258  template <typename T, typename... Args>
3259  IsMember(std::initializer_list<T> values, Args &&...args)
3260  : IsMember(std::vector<T>(values), std::forward<Args>(args)...) {}
3261 
3262  /// This checks to see if an item is in a set (empty function)
3263  template <typename T> explicit IsMember(T &&set) : IsMember(std::forward<T>(set), nullptr) {}
3264 
3265  /// This checks to see if an item is in a set: pointer or copy version. You can pass in a function that will filter
3266  /// both sides of the comparison before computing the comparison.
3267  template <typename T, typename F> explicit IsMember(T set, F filter_function) {
3268 
3269  // Get the type of the contained item - requires a container have ::value_type
3270  // if the type does not have first_type and second_type, these are both value_type
3271  using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
3272  using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
3273 
3274  using local_item_t = typename IsMemberType<item_t>::type; // This will convert bad types to good ones
3275  // (const char * to std::string)
3276 
3277  // Make a local copy of the filter function, using a std::function if not one already
3278  std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3279 
3280  // This is the type name for help, it will take the current version of the set contents
3281  desc_function_ = [set]() { return detail::generate_set(detail::smart_deref(set)); };
3282 
3283  // This is the function that validates
3284  // It stores a copy of the set pointer-like, so shared_ptr will stay alive
3285  func_ = [set, filter_fn](std::string &input) {
3286  local_item_t b;
3287  if(!detail::lexical_cast(input, b)) {
3288  throw ValidationError(input); // name is added later
3289  }
3290  if(filter_fn) {
3291  b = filter_fn(b);
3292  }
3293  auto res = detail::search(set, b, filter_fn);
3294  if(res.first) {
3295  // Make sure the version in the input string is identical to the one in the set
3296  if(filter_fn) {
3298  }
3299 
3300  // Return empty error string (success)
3301  return std::string{};
3302  }
3303 
3304  // If you reach this point, the result was not found
3305  return input + " not in " + detail::generate_set(detail::smart_deref(set));
3306  };
3307  }
3308 
3309  /// You can pass in as many filter functions as you like, they nest (string only currently)
3310  template <typename T, typename... Args>
3311  IsMember(T &&set, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
3312  : IsMember(
3313  std::forward<T>(set),
3314  [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
3315  other...) {}
3316 };
3317 
3318 /// definition of the default transformation object
3319 template <typename T> using TransformPairs = std::vector<std::pair<std::string, T>>;
3320 
3321 /// Translate named items to other or a value set
3322 class Transformer : public Validator {
3323  public:
3324  using filter_fn_t = std::function<std::string(std::string)>;
3325 
3326  /// This allows in-place construction
3327  template <typename... Args>
3328  Transformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&...args)
3329  : Transformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
3330 
3331  /// direct map of std::string to std::string
3332  template <typename T> explicit Transformer(T &&mapping) : Transformer(std::forward<T>(mapping), nullptr) {}
3333 
3334  /// This checks to see if an item is in a set: pointer or copy version. You can pass in a function that will filter
3335  /// both sides of the comparison before computing the comparison.
3336  template <typename T, typename F> explicit Transformer(T mapping, F filter_function) {
3337 
3338  static_assert(detail::pair_adaptor<typename detail::element_type<T>::type>::value,
3339  "mapping must produce value pairs");
3340  // Get the type of the contained item - requires a container have ::value_type
3341  // if the type does not have first_type and second_type, these are both value_type
3342  using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
3343  using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
3344  using local_item_t = typename IsMemberType<item_t>::type; // Will convert bad types to good ones
3345  // (const char * to std::string)
3346 
3347  // Make a local copy of the filter function, using a std::function if not one already
3348  std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3349 
3350  // This is the type name for help, it will take the current version of the set contents
3351  desc_function_ = [mapping]() { return detail::generate_map(detail::smart_deref(mapping)); };
3352 
3353  func_ = [mapping, filter_fn](std::string &input) {
3354  local_item_t b;
3355  if(!detail::lexical_cast(input, b)) {
3356  return std::string();
3357  // there is no possible way we can match anything in the mapping if we can't convert so just return
3358  }
3359  if(filter_fn) {
3360  b = filter_fn(b);
3361  }
3362  auto res = detail::search(mapping, b, filter_fn);
3363  if(res.first) {
3365  }
3366  return std::string{};
3367  };
3368  }
3369 
3370  /// You can pass in as many filter functions as you like, they nest
3371  template <typename T, typename... Args>
3372  Transformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
3373  : Transformer(
3374  std::forward<T>(mapping),
3375  [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
3376  other...) {}
3377 };
3378 
3379 /// translate named items to other or a value set
3381  public:
3382  using filter_fn_t = std::function<std::string(std::string)>;
3383 
3384  /// This allows in-place construction
3385  template <typename... Args>
3386  CheckedTransformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&...args)
3387  : CheckedTransformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
3388 
3389  /// direct map of std::string to std::string
3390  template <typename T> explicit CheckedTransformer(T mapping) : CheckedTransformer(std::move(mapping), nullptr) {}
3391 
3392  /// This checks to see if an item is in a set: pointer or copy version. You can pass in a function that will filter
3393  /// both sides of the comparison before computing the comparison.
3394  template <typename T, typename F> explicit CheckedTransformer(T mapping, F filter_function) {
3395 
3396  static_assert(detail::pair_adaptor<typename detail::element_type<T>::type>::value,
3397  "mapping must produce value pairs");
3398  // Get the type of the contained item - requires a container have ::value_type
3399  // if the type does not have first_type and second_type, these are both value_type
3400  using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
3401  using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
3402  using local_item_t = typename IsMemberType<item_t>::type; // Will convert bad types to good ones
3403  // (const char * to std::string)
3404  using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
3405 
3406  // Make a local copy of the filter function, using a std::function if not one already
3407  std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3408 
3409  auto tfunc = [mapping]() {
3410  std::string out("value in ");
3411  out += detail::generate_map(detail::smart_deref(mapping)) + " OR {";
3412  out += detail::join(
3413  detail::smart_deref(mapping),
3414  [](const iteration_type_t &v) { return detail::to_string(detail::pair_adaptor<element_t>::second(v)); },
3415  ",");
3416  out.push_back('}');
3417  return out;
3418  };
3419 
3420  desc_function_ = tfunc;
3421 
3422  func_ = [mapping, tfunc, filter_fn](std::string &input) {
3423  local_item_t b;
3424  bool converted = detail::lexical_cast(input, b);
3425  if(converted) {
3426  if(filter_fn) {
3427  b = filter_fn(b);
3428  }
3429  auto res = detail::search(mapping, b, filter_fn);
3430  if(res.first) {
3432  return std::string{};
3433  }
3434  }
3435  for(const auto &v : detail::smart_deref(mapping)) {
3437  if(output_string == input) {
3438  return std::string();
3439  }
3440  }
3441 
3442  return "Check " + input + " " + tfunc() + " FAILED";
3443  };
3444  }
3445 
3446  /// You can pass in as many filter functions as you like, they nest
3447  template <typename T, typename... Args>
3448  CheckedTransformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
3450  std::forward<T>(mapping),
3451  [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
3452  other...) {}
3453 };
3454 
3455 /// Helper function to allow ignore_case to be passed to IsMember or Transform
3456 inline std::string ignore_case(std::string item) { return detail::to_lower(item); }
3457 
3458 /// Helper function to allow ignore_underscore to be passed to IsMember or Transform
3460 
3461 /// Helper function to allow checks to ignore spaces to be passed to IsMember or Transform
3463  item.erase(std::remove(std::begin(item), std::end(item), ' '), std::end(item));
3464  item.erase(std::remove(std::begin(item), std::end(item), '\t'), std::end(item));
3465  return item;
3466 }
3467 
3468 /// Multiply a number by a factor using given mapping.
3469 /// Can be used to write transforms for SIZE or DURATION inputs.
3470 ///
3471 /// Example:
3472 /// With mapping = `{"b"->1, "kb"->1024, "mb"->1024*1024}`
3473 /// one can recognize inputs like "100", "12kb", "100 MB",
3474 /// that will be automatically transformed to 100, 14448, 104857600.
3475 ///
3476 /// Output number type matches the type in the provided mapping.
3477 /// Therefore, if it is required to interpret real inputs like "0.42 s",
3478 /// the mapping should be of a type <string, float> or <string, double>.
3479 class AsNumberWithUnit : public Validator {
3480  public:
3481  /// Adjust AsNumberWithUnit behavior.
3482  /// CASE_SENSITIVE/CASE_INSENSITIVE controls how units are matched.
3483  /// UNIT_OPTIONAL/UNIT_REQUIRED throws ValidationError
3484  /// if UNIT_REQUIRED is set and unit literal is not found.
3485  enum Options {
3486  CASE_SENSITIVE = 0,
3487  CASE_INSENSITIVE = 1,
3488  UNIT_OPTIONAL = 0,
3489  UNIT_REQUIRED = 2,
3490  DEFAULT = CASE_INSENSITIVE | UNIT_OPTIONAL
3491  };
3492 
3493  template <typename Number>
3494  explicit AsNumberWithUnit(std::map<std::string, Number> mapping,
3495  Options opts = DEFAULT,
3496  const std::string &unit_name = "UNIT") {
3497  description(generate_description<Number>(unit_name, opts));
3498  validate_mapping(mapping, opts);
3499 
3500  // transform function
3501  func_ = [mapping, opts](std::string &input) -> std::string {
3502  Number num{};
3503 
3504  detail::rtrim(input);
3505  if(input.empty()) {
3506  throw ValidationError("Input is empty");
3507  }
3508 
3509  // Find split position between number and prefix
3510  auto unit_begin = input.end();
3511  while(unit_begin > input.begin() && std::isalpha(*(unit_begin - 1), std::locale())) {
3512  --unit_begin;
3513  }
3514 
3515  std::string unit{unit_begin, input.end()};
3516  input.resize(static_cast<std::size_t>(std::distance(input.begin(), unit_begin)));
3517  detail::trim(input);
3518 
3519  if(opts & UNIT_REQUIRED && unit.empty()) {
3520  throw ValidationError("Missing mandatory unit");
3521  }
3522  if(opts & CASE_INSENSITIVE) {
3524  }
3525  if(unit.empty()) {
3526  if(!detail::lexical_cast(input, num)) {
3527  throw ValidationError(std::string("Value ") + input + " could not be converted to " +
3528  detail::type_name<Number>());
3529  }
3530  // No need to modify input if no unit passed
3531  return {};
3532  }
3533 
3534  // find corresponding factor
3535  auto it = mapping.find(unit);
3536  if(it == mapping.end()) {
3537  throw ValidationError(unit +
3538  " unit not recognized. "
3539  "Allowed values: " +
3540  detail::generate_map(mapping, true));
3541  }
3542 
3543  if(!input.empty()) {
3544  bool converted = detail::lexical_cast(input, num);
3545  if(!converted) {
3546  throw ValidationError(std::string("Value ") + input + " could not be converted to " +
3547  detail::type_name<Number>());
3548  }
3549  // perform safe multiplication
3550  bool ok = detail::checked_multiply(num, it->second);
3551  if(!ok) {
3552  throw ValidationError(detail::to_string(num) + " multiplied by " + unit +
3553  " factor would cause number overflow. Use smaller value.");
3554  }
3555  } else {
3556  num = static_cast<Number>(it->second);
3557  }
3558 
3559  input = detail::to_string(num);
3560 
3561  return {};
3562  };
3563  }
3564 
3565  private:
3566  /// Check that mapping contains valid units.
3567  /// Update mapping for CASE_INSENSITIVE mode.
3568  template <typename Number> static void validate_mapping(std::map<std::string, Number> &mapping, Options opts) {
3569  for(auto &kv : mapping) {
3570  if(kv.first.empty()) {
3571  throw ValidationError("Unit must not be empty.");
3572  }
3573  if(!detail::isalpha(kv.first)) {
3574  throw ValidationError("Unit must contain only letters.");
3575  }
3576  }
3577 
3578  // make all units lowercase if CASE_INSENSITIVE
3579  if(opts & CASE_INSENSITIVE) {
3580  std::map<std::string, Number> lower_mapping;
3581  for(auto &kv : mapping) {
3582  auto s = detail::to_lower(kv.first);
3583  if(lower_mapping.count(s)) {
3584  throw ValidationError(std::string("Several matching lowercase unit representations are found: ") +
3585  s);
3586  }
3587  lower_mapping[detail::to_lower(kv.first)] = kv.second;
3588  }
3589  mapping = std::move(lower_mapping);
3590  }
3591  }
3592 
3593  /// Generate description like this: NUMBER [UNIT]
3594  template <typename Number> static std::string generate_description(const std::string &name, Options opts) {
3595  std::stringstream out;
3596  out << detail::type_name<Number>() << ' ';
3597  if(opts & UNIT_REQUIRED) {
3598  out << name;
3599  } else {
3600  out << '[' << name << ']';
3601  }
3602  return out.str();
3603  }
3604 };
3605 
3607  return static_cast<AsNumberWithUnit::Options>(static_cast<int>(a) | static_cast<int>(b));
3608 }
3609 
3610 /// Converts a human-readable size string (with unit literal) to uin64_t size.
3611 /// Example:
3612 /// "100" => 100
3613 /// "1 b" => 100
3614 /// "10Kb" => 10240 // you can configure this to be interpreted as kilobyte (*1000) or kibibyte (*1024)
3615 /// "10 KB" => 10240
3616 /// "10 kb" => 10240
3617 /// "10 kib" => 10240 // *i, *ib are always interpreted as *bibyte (*1024)
3618 /// "10kb" => 10240
3619 /// "2 MB" => 2097152
3620 /// "2 EiB" => 2^61 // Units up to exibyte are supported
3622  public:
3623  using result_t = std::uint64_t;
3624 
3625  /// If kb_is_1000 is true,
3626  /// interpret 'kb', 'k' as 1000 and 'kib', 'ki' as 1024
3627  /// (same applies to higher order units as well).
3628  /// Otherwise, interpret all literals as factors of 1024.
3629  /// The first option is formally correct, but
3630  /// the second interpretation is more wide-spread
3631  /// (see https://en.wikipedia.org/wiki/Binary_prefix).
3632  explicit AsSizeValue(bool kb_is_1000);
3633 
3634  private:
3635  /// Get <size unit, factor> mapping
3636  static std::map<std::string, result_t> init_mapping(bool kb_is_1000);
3637 
3638  /// Cache calculated mapping
3639  static std::map<std::string, result_t> get_mapping(bool kb_is_1000);
3640 };
3641 
3642 namespace detail {
3643 /// Split a string into a program name and command line arguments
3644 /// the string is assumed to contain a file name followed by other arguments
3645 /// the return value contains is a pair with the first argument containing the program name and the second
3646 /// everything else.
3647 CLI11_INLINE std::pair<std::string, std::string> split_program_name(std::string commandline);
3648 
3649 } // namespace detail
3650 /// @}
3651 
3652 
3653 
3654 
3656  std::string retstring;
3657  if(active_) {
3658  if(non_modifying_) {
3659  std::string value = str;
3660  retstring = func_(value);
3661  } else {
3662  retstring = func_(str);
3663  }
3664  }
3665  return retstring;
3666 }
3667 
3669  Validator newval(*this);
3670  newval.desc_function_ = [validator_desc]() { return validator_desc; };
3671  return newval;
3672 }
3673 
3675  Validator newval;
3676 
3677  newval._merge_description(*this, other, " AND ");
3678 
3679  // Give references (will make a copy in lambda function)
3680  const std::function<std::string(std::string & filename)> &f1 = func_;
3681  const std::function<std::string(std::string & filename)> &f2 = other.func_;
3682 
3683  newval.func_ = [f1, f2](std::string &input) {
3684  std::string s1 = f1(input);
3685  std::string s2 = f2(input);
3686  if(!s1.empty() && !s2.empty())
3687  return std::string("(") + s1 + ") AND (" + s2 + ")";
3688  return s1 + s2;
3689  };
3690 
3691  newval.active_ = active_ && other.active_;
3692  newval.application_index_ = application_index_;
3693  return newval;
3694 }
3695 
3697  Validator newval;
3698 
3699  newval._merge_description(*this, other, " OR ");
3700 
3701  // Give references (will make a copy in lambda function)
3702  const std::function<std::string(std::string &)> &f1 = func_;
3703  const std::function<std::string(std::string &)> &f2 = other.func_;
3704 
3705  newval.func_ = [f1, f2](std::string &input) {
3706  std::string s1 = f1(input);
3707  std::string s2 = f2(input);
3708  if(s1.empty() || s2.empty())
3709  return std::string();
3710 
3711  return std::string("(") + s1 + ") OR (" + s2 + ")";
3712  };
3713  newval.active_ = active_ && other.active_;
3714  newval.application_index_ = application_index_;
3715  return newval;
3716 }
3717 
3719  Validator newval;
3720  const std::function<std::string()> &dfunc1 = desc_function_;
3721  newval.desc_function_ = [dfunc1]() {
3722  auto str = dfunc1();
3723  return (!str.empty()) ? std::string("NOT ") + str : std::string{};
3724  };
3725  // Give references (will make a copy in lambda function)
3726  const std::function<std::string(std::string & res)> &f1 = func_;
3727 
3728  newval.func_ = [f1, dfunc1](std::string &test) -> std::string {
3729  std::string s1 = f1(test);
3730  if(s1.empty()) {
3731  return std::string("check ") + dfunc1() + " succeeded improperly";
3732  }
3733  return std::string{};
3734  };
3735  newval.active_ = active_;
3736  newval.application_index_ = application_index_;
3737  return newval;
3738 }
3739 
3740 CLI11_INLINE void
3741 Validator::_merge_description(const Validator &val1, const Validator &val2, const std::string &merger) {
3742 
3743  const std::function<std::string()> &dfunc1 = val1.desc_function_;
3744  const std::function<std::string()> &dfunc2 = val2.desc_function_;
3745 
3746  desc_function_ = [=]() {
3747  std::string f1 = dfunc1();
3748  std::string f2 = dfunc2();
3749  if((f1.empty()) || (f2.empty())) {
3750  return f1 + f2;
3751  }
3752  return std::string(1, '(') + f1 + ')' + merger + '(' + f2 + ')';
3753  };
3754 }
3755 
3756 namespace detail {
3757 
3758 #if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
3759 CLI11_INLINE path_type check_path(const char *file) noexcept {
3760  std::error_code ec;
3761  auto stat = std::filesystem::status(file, ec);
3762  if(ec) {
3763  return path_type::nonexistent;
3764  }
3765  switch(stat.type()) {
3766  case std::filesystem::file_type::none: // LCOV_EXCL_LINE
3767  case std::filesystem::file_type::not_found:
3768  return path_type::nonexistent;
3769  case std::filesystem::file_type::directory:
3770  return path_type::directory;
3771  case std::filesystem::file_type::symlink:
3772  case std::filesystem::file_type::block:
3773  case std::filesystem::file_type::character:
3774  case std::filesystem::file_type::fifo:
3775  case std::filesystem::file_type::socket:
3776  case std::filesystem::file_type::regular:
3777  case std::filesystem::file_type::unknown:
3778  default:
3779  return path_type::file;
3780  }
3781 }
3782 #else
3783 CLI11_INLINE path_type check_path(const char *file) noexcept {
3784 #if defined(_MSC_VER)
3785  struct __stat64 buffer;
3786  if(_stat64(file, &buffer) == 0) {
3787  return ((buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
3788  }
3789 #else
3790  struct stat buffer;
3791  if(stat(file, &buffer) == 0) {
3792  return ((buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
3793  }
3794 #endif
3795  return path_type::nonexistent;
3796 }
3797 #endif
3798 
3800  func_ = [](std::string &filename) {
3801  auto path_result = check_path(filename.c_str());
3802  if(path_result == path_type::nonexistent) {
3803  return "File does not exist: " + filename;
3804  }
3805  if(path_result == path_type::directory) {
3806  return "File is actually a directory: " + filename;
3807  }
3808  return std::string();
3809  };
3810 }
3811 
3813  func_ = [](std::string &filename) {
3814  auto path_result = check_path(filename.c_str());
3815  if(path_result == path_type::nonexistent) {
3816  return "Directory does not exist: " + filename;
3817  }
3818  if(path_result == path_type::file) {
3819  return "Directory is actually a file: " + filename;
3820  }
3821  return std::string();
3822  };
3823 }
3824 
3826  func_ = [](std::string &filename) {
3827  auto path_result = check_path(filename.c_str());
3828  if(path_result == path_type::nonexistent) {
3829  return "Path does not exist: " + filename;
3830  }
3831  return std::string();
3832  };
3833 }
3834 
3836  func_ = [](std::string &filename) {
3837  auto path_result = check_path(filename.c_str());
3838  if(path_result != path_type::nonexistent) {
3839  return "Path already exists: " + filename;
3840  }
3841  return std::string();
3842  };
3843 }
3844 
3846  func_ = [](std::string &ip_addr) {
3847  auto result = CLI::detail::split(ip_addr, '.');
3848  if(result.size() != 4) {
3849  return std::string("Invalid IPV4 address must have four parts (") + ip_addr + ')';
3850  }
3851  int num = 0;
3852  for(const auto &var : result) {
3853  bool retval = detail::lexical_cast(var, num);
3854  if(!retval) {
3855  return std::string("Failed parsing number (") + var + ')';
3856  }
3857  if(num < 0 || num > 255) {
3858  return std::string("Each IP number must be between 0 and 255 ") + var;
3859  }
3860  }
3861  return std::string();
3862  };
3863 }
3864 
3865 } // namespace detail
3866 
3868  : Validator("FILE") {
3869  func_ = [default_path, enableErrorReturn](std::string &filename) {
3870  auto path_result = detail::check_path(filename.c_str());
3871  if(path_result == detail::path_type::nonexistent) {
3872  std::string test_file_path = default_path;
3873  if(default_path.back() != '/' && default_path.back() != '\\') {
3874  // Add folder separator
3875  test_file_path += '/';
3876  }
3877  test_file_path.append(filename);
3878  path_result = detail::check_path(test_file_path.c_str());
3879  if(path_result == detail::path_type::file) {
3880  filename = test_file_path;
3881  } else {
3882  if(enableErrorReturn) {
3883  return "File does not exist: " + filename;
3884  }
3885  }
3886  }
3887  return std::string{};
3888  };
3889 }
3890 
3891 CLI11_INLINE AsSizeValue::AsSizeValue(bool kb_is_1000) : AsNumberWithUnit(get_mapping(kb_is_1000)) {
3892  if(kb_is_1000) {
3893  description("SIZE [b, kb(=1000b), kib(=1024b), ...]");
3894  } else {
3895  description("SIZE [b, kb(=1024b), ...]");
3896  }
3897 }
3898 
3899 CLI11_INLINE std::map<std::string, AsSizeValue::result_t> AsSizeValue::init_mapping(bool kb_is_1000) {
3900  std::map<std::string, result_t> m;
3901  result_t k_factor = kb_is_1000 ? 1000 : 1024;
3902  result_t ki_factor = 1024;
3903  result_t k = 1;
3904  result_t ki = 1;
3905  m["b"] = 1;
3906  for(std::string p : {"k", "m", "g", "t", "p", "e"}) {
3907  k *= k_factor;
3908  ki *= ki_factor;
3909  m[p] = k;
3910  m[p + "b"] = k;
3911  m[p + "i"] = ki;
3912  m[p + "ib"] = ki;
3913  }
3914  return m;
3915 }
3916 
3917 CLI11_INLINE std::map<std::string, AsSizeValue::result_t> AsSizeValue::get_mapping(bool kb_is_1000) {
3918  if(kb_is_1000) {
3919  static auto m = init_mapping(true);
3920  return m;
3921  }
3922  static auto m = init_mapping(false);
3923  return m;
3924 }
3925 
3926 namespace detail {
3927 
3928 CLI11_INLINE std::pair<std::string, std::string> split_program_name(std::string commandline) {
3929  // try to determine the programName
3930  std::pair<std::string, std::string> vals;
3931  trim(commandline);
3932  auto esp = commandline.find_first_of(' ', 1);
3933  while(detail::check_path(commandline.substr(0, esp).c_str()) != path_type::file) {
3934  esp = commandline.find_first_of(' ', esp + 1);
3935  if(esp == std::string::npos) {
3936  // if we have reached the end and haven't found a valid file just assume the first argument is the
3937  // program name
3938  if(commandline[0] == '"' || commandline[0] == '\'' || commandline[0] == '`') {
3939  bool embeddedQuote = false;
3940  auto keyChar = commandline[0];
3941  auto end = commandline.find_first_of(keyChar, 1);
3942  while((end != std::string::npos) && (commandline[end - 1] == '\\')) { // deal with escaped quotes
3943  end = commandline.find_first_of(keyChar, end + 1);
3944  embeddedQuote = true;
3945  }
3946  if(end != std::string::npos) {
3947  vals.first = commandline.substr(1, end - 1);
3948  esp = end + 1;
3949  if(embeddedQuote) {
3950  vals.first = find_and_replace(vals.first, std::string("\\") + keyChar, std::string(1, keyChar));
3951  }
3952  } else {
3953  esp = commandline.find_first_of(' ', 1);
3954  }
3955  } else {
3956  esp = commandline.find_first_of(' ', 1);
3957  }
3958 
3959  break;
3960  }
3961  }
3962  if(vals.first.empty()) {
3963  vals.first = commandline.substr(0, esp);
3964  rtrim(vals.first);
3965  }
3966 
3967  // strip the program name
3968  vals.second = (esp < commandline.length() - 1) ? commandline.substr(esp + 1) : std::string{};
3969  ltrim(vals.second);
3970  return vals;
3971 }
3972 
3973 } // namespace detail
3974 /// @}
3975 
3976 
3977 
3978 
3979 class Option;
3980 class App;
3981 
3982 /// This enum signifies the type of help requested
3983 ///
3984 /// This is passed in by App; all user classes must accept this as
3985 /// the second argument.
3986 
3987 enum class AppFormatMode {
3988  Normal, ///< The normal, detailed help
3989  All, ///< A fully expanded help
3990  Sub, ///< Used when printed as part of expanded subcommand
3991 };
3992 
3993 /// This is the minimum requirements to run a formatter.
3994 ///
3995 /// A user can subclass this is if they do not care at all
3996 /// about the structure in CLI::Formatter.
3998  protected:
3999  /// @name Options
4000  ///@{
4001 
4002  /// The width of the first column
4003  std::size_t column_width_{30};
4004 
4005  /// @brief The required help printout labels (user changeable)
4006  /// Values are Needs, Excludes, etc.
4007  std::map<std::string, std::string> labels_{};
4008 
4009  ///@}
4010  /// @name Basic
4011  ///@{
4012 
4013  public:
4014  FormatterBase() = default;
4015  FormatterBase(const FormatterBase &) = default;
4016  FormatterBase(FormatterBase &&) = default;
4017  FormatterBase &operator=(const FormatterBase &) = default;
4018  FormatterBase &operator=(FormatterBase &&) = default;
4019 
4020  /// Adding a destructor in this form to work around bug in GCC 4.7
4021  virtual ~FormatterBase() noexcept {} // NOLINT(modernize-use-equals-default)
4022 
4023  /// This is the key method that puts together help
4024  virtual std::string make_help(const App *, std::string, AppFormatMode) const = 0;
4025 
4026  ///@}
4027  /// @name Setters
4028  ///@{
4029 
4030  /// Set the "REQUIRED" label
4031  void label(std::string key, std::string val) { labels_[key] = val; }
4032 
4033  /// Set the column width
4034  void column_width(std::size_t val) { column_width_ = val; }
4035 
4036  ///@}
4037  /// @name Getters
4038  ///@{
4039 
4040  /// Get the current value of a name (REQUIRED, etc.)
4042  if(labels_.find(key) == labels_.end())
4043  return key;
4044  return labels_.at(key);
4045  }
4046 
4047  /// Get the current column width
4048  CLI11_NODISCARD std::size_t get_column_width() const { return column_width_; }
4049 
4050  ///@}
4051 };
4052 
4053 /// This is a specialty override for lambda functions
4054 class FormatterLambda final : public FormatterBase {
4055  using funct_t = std::function<std::string(const App *, std::string, AppFormatMode)>;
4056 
4057  /// The lambda to hold and run
4058  funct_t lambda_;
4059 
4060  public:
4061  /// Create a FormatterLambda with a lambda function
4062  explicit FormatterLambda(funct_t funct) : lambda_(std::move(funct)) {}
4063 
4064  /// Adding a destructor (mostly to make GCC 4.7 happy)
4065  ~FormatterLambda() noexcept override {} // NOLINT(modernize-use-equals-default)
4066 
4067  /// This will simply call the lambda function
4068  std::string make_help(const App *app, std::string name, AppFormatMode mode) const override {
4069  return lambda_(app, name, mode);
4070  }
4071 };
4072 
4073 /// This is the default Formatter for CLI11. It pretty prints help output, and is broken into quite a few
4074 /// overridable methods, to be highly customizable with minimal effort.
4075 class Formatter : public FormatterBase {
4076  public:
4077  Formatter() = default;
4078  Formatter(const Formatter &) = default;
4079  Formatter(Formatter &&) = default;
4080  Formatter &operator=(const Formatter &) = default;
4081  Formatter &operator=(Formatter &&) = default;
4082 
4083  /// @name Overridables
4084  ///@{
4085 
4086  /// This prints out a group of options with title
4087  ///
4089  make_group(std::string group, bool is_positional, std::vector<const Option *> opts) const;
4090 
4091  /// This prints out just the positionals "group"
4092  virtual std::string make_positionals(const App *app) const;
4093 
4094  /// This prints out all the groups of options
4095  std::string make_groups(const App *app, AppFormatMode mode) const;
4096 
4097  /// This prints out all the subcommands
4098  virtual std::string make_subcommands(const App *app, AppFormatMode mode) const;
4099 
4100  /// This prints out a subcommand
4101  virtual std::string make_subcommand(const App *sub) const;
4102 
4103  /// This prints out a subcommand in help-all
4104  virtual std::string make_expanded(const App *sub) const;
4105 
4106  /// This prints out all the groups of options
4107  virtual std::string make_footer(const App *app) const;
4108 
4109  /// This displays the description line
4110  virtual std::string make_description(const App *app) const;
4111 
4112  /// This displays the usage line
4113  virtual std::string make_usage(const App *app, std::string name) const;
4114 
4115  /// This puts everything together
4116  std::string make_help(const App * /*app*/, std::string, AppFormatMode) const override;
4117 
4118  ///@}
4119  /// @name Options
4120  ///@{
4121 
4122  /// This prints out an option help line, either positional or optional form
4123  virtual std::string make_option(const Option *opt, bool is_positional) const {
4124  std::stringstream out;
4126  out, make_option_name(opt, is_positional) + make_option_opts(opt), make_option_desc(opt), column_width_);
4127  return out.str();
4128  }
4129 
4130  /// @brief This is the name part of an option, Default: left column
4131  virtual std::string make_option_name(const Option *, bool) const;
4132 
4133  /// @brief This is the options part of the name, Default: combined into left column
4134  virtual std::string make_option_opts(const Option *) const;
4135 
4136  /// @brief This is the description. Default: Right column, on new line if left column too large
4137  virtual std::string make_option_desc(const Option *) const;
4138 
4139  /// @brief This is used to print the name on the USAGE line
4140  virtual std::string make_option_usage(const Option *opt) const;
4141 
4142  ///@}
4143 };
4144 
4145 
4146 
4147 
4148 using results_t = std::vector<std::string>;
4149 /// callback function definition
4150 using callback_t = std::function<bool(const results_t &)>;
4151 
4152 class Option;
4153 class App;
4154 
4155 using Option_p = std::unique_ptr<Option>;
4156 /// Enumeration of the multiOption Policy selection
4157 enum class MultiOptionPolicy : char {
4158  Throw, //!< Throw an error if any extra arguments were given
4159  TakeLast, //!< take only the last Expected number of arguments
4160  TakeFirst, //!< take only the first Expected number of arguments
4161  Join, //!< merge all the arguments together into a single string via the delimiter character default('\n')
4162  TakeAll, //!< just get all the passed argument regardless
4163  Sum //!< sum all the arguments together if numerical or concatenate directly without delimiter
4164 };
4165 
4166 /// This is the CRTP base class for Option and OptionDefaults. It was designed this way
4167 /// to share parts of the class; an OptionDefaults can copy to an Option.
4168 template <typename CRTP> class OptionBase {
4169  friend App;
4170 
4171  protected:
4172  /// The group membership
4174 
4175  /// True if this is a required option
4176  bool required_{false};
4177 
4178  /// Ignore the case when matching (option, not value)
4179  bool ignore_case_{false};
4180 
4181  /// Ignore underscores when matching (option, not value)
4182  bool ignore_underscore_{false};
4183 
4184  /// Allow this option to be given in a configuration file
4185  bool configurable_{true};
4186 
4187  /// Disable overriding flag values with '=value'
4189 
4190  /// Specify a delimiter character for vector arguments
4191  char delimiter_{'\0'};
4192 
4193  /// Automatically capture default value
4195 
4196  /// Policy for handling multiple arguments beyond the expected Max
4198 
4199  /// Copy the contents to another similar class (one based on OptionBase)
4200  template <typename T> void copy_to(T *other) const;
4201 
4202  public:
4203  // setters
4204 
4205  /// Changes the group membership
4206  CRTP *group(const std::string &name) {
4207  if(!detail::valid_alias_name_string(name)) {
4208  throw IncorrectConstruction("Group names may not contain newlines or null characters");
4209  }
4210  group_ = name;
4211  return static_cast<CRTP *>(this);
4212  }
4213 
4214  /// Set the option as required
4215  CRTP *required(bool value = true) {
4216  required_ = value;
4217  return static_cast<CRTP *>(this);
4218  }
4219 
4220  /// Support Plumbum term
4221  CRTP *mandatory(bool value = true) { return required(value); }
4222 
4223  CRTP *always_capture_default(bool value = true) {
4225  return static_cast<CRTP *>(this);
4226  }
4227 
4228  // Getters
4229 
4230  /// Get the group of this option
4231  CLI11_NODISCARD const std::string &get_group() const { return group_; }
4232 
4233  /// True if this is a required option
4234  CLI11_NODISCARD bool get_required() const { return required_; }
4235 
4236  /// The status of ignore case
4238 
4239  /// The status of ignore_underscore
4241 
4242  /// The status of configurable
4244 
4245  /// The status of configurable
4247 
4248  /// Get the current delimiter char
4249  CLI11_NODISCARD char get_delimiter() const { return delimiter_; }
4250 
4251  /// Return true if this will automatically capture the default value for help printing
4253 
4254  /// The status of the multi option policy
4256 
4257  // Shortcuts for multi option policy
4258 
4259  /// Set the multi option policy to take last
4260  CRTP *take_last() {
4261  auto *self = static_cast<CRTP *>(this);
4263  return self;
4264  }
4265 
4266  /// Set the multi option policy to take last
4267  CRTP *take_first() {
4268  auto *self = static_cast<CRTP *>(this);
4270  return self;
4271  }
4272 
4273  /// Set the multi option policy to take all arguments
4274  CRTP *take_all() {
4275  auto self = static_cast<CRTP *>(this);
4277  return self;
4278  }
4279 
4280  /// Set the multi option policy to join
4281  CRTP *join() {
4282  auto *self = static_cast<CRTP *>(this);
4284  return self;
4285  }
4286 
4287  /// Set the multi option policy to join with a specific delimiter
4288  CRTP *join(char delim) {
4289  auto self = static_cast<CRTP *>(this);
4290  self->delimiter_ = delim;
4291  self->multi_option_policy(MultiOptionPolicy::Join);
4292  return self;
4293  }
4294 
4295  /// Allow in a configuration file
4296  CRTP *configurable(bool value = true) {
4297  configurable_ = value;
4298  return static_cast<CRTP *>(this);
4299  }
4300 
4301  /// Allow in a configuration file
4302  CRTP *delimiter(char value = '\0') {
4303  delimiter_ = value;
4304  return static_cast<CRTP *>(this);
4305  }
4306 };
4307 
4308 /// This is a version of OptionBase that only supports setting values,
4309 /// for defaults. It is stored as the default option in an App.
4310 class OptionDefaults : public OptionBase<OptionDefaults> {
4311  public:
4312  OptionDefaults() = default;
4313 
4314  // Methods here need a different implementation if they are Option vs. OptionDefault
4315 
4316  /// Take the last argument if given multiple times
4319  return this;
4320  }
4321 
4322  /// Ignore the case of the option name
4323  OptionDefaults *ignore_case(bool value = true) {
4324  ignore_case_ = value;
4325  return this;
4326  }
4327 
4328  /// Ignore underscores in the option name
4329  OptionDefaults *ignore_underscore(bool value = true) {
4331  return this;
4332  }
4333 
4334  /// Disable overriding flag values with an '=<value>' segment
4337  return this;
4338  }
4339 
4340  /// set a delimiter character to split up single arguments to treat as multiple inputs
4341  OptionDefaults *delimiter(char value = '\0') {
4342  delimiter_ = value;
4343  return this;
4344  }
4345 };
4346 
4347 class Option : public OptionBase<Option> {
4348  friend App;
4349 
4350  protected:
4351  /// @name Names
4352  ///@{
4353 
4354  /// A list of the short names (`-a`) without the leading dashes
4355  std::vector<std::string> snames_{};
4356 
4357  /// A list of the long names (`--long`) without the leading dashes
4358  std::vector<std::string> lnames_{};
4359 
4360  /// A list of the flag names with the appropriate default value, the first part of the pair should be duplicates of
4361  /// what is in snames or lnames but will trigger a particular response on a flag
4362  std::vector<std::pair<std::string, std::string>> default_flag_values_{};
4363 
4364  /// a list of flag names with specified default values;
4365  std::vector<std::string> fnames_{};
4366 
4367  /// A positional name
4369 
4370  /// If given, check the environment for this option
4372 
4373  ///@}
4374  /// @name Help
4375  ///@{
4376 
4377  /// The description for help strings
4379 
4380  /// A human readable default value, either manually set, captured, or captured by default
4382 
4383  /// If given, replace the text that describes the option type and usage in the help text
4385 
4386  /// A human readable type value, set when App creates this
4387  ///
4388  /// This is a lambda function so "types" can be dynamic, such as when a set prints its contents.
4389  std::function<std::string()> type_name_{[]() { return std::string(); }};
4390 
4391  /// Run this function to capture a default (ignore if empty)
4392  std::function<std::string()> default_function_{};
4393 
4394  ///@}
4395  /// @name Configuration
4396  ///@{
4397 
4398  /// The number of arguments that make up one option. max is the nominal type size, min is the minimum number of
4399  /// strings
4401  /// The minimum number of arguments an option should be expecting
4403 
4404  /// The minimum number of expected values
4406  /// The maximum number of expected values
4408 
4409  /// A list of Validators to run on each value parsed
4410  std::vector<Validator> validators_{};
4411 
4412  /// A list of options that are required with this option
4413  std::set<Option *> needs_{};
4414 
4415  /// A list of options that are excluded with this option
4416  std::set<Option *> excludes_{};
4417 
4418  ///@}
4419  /// @name Other
4420  ///@{
4421 
4422  /// link back up to the parent App for fallthrough
4423  App *parent_{nullptr};
4424 
4425  /// Options store a callback to do all the work
4427 
4428  ///@}
4429  /// @name Parsing results
4430  ///@{
4431 
4432  /// complete Results of parsing
4434  /// results after reduction
4436  /// enumeration for the option state machine
4437  enum class option_state : char {
4438  parsing = 0, //!< The option is currently collecting parsed results
4439  validated = 2, //!< the results have been validated
4440  reduced = 4, //!< a subset of results has been generated
4441  callback_run = 6, //!< the callback has been executed
4442  };
4443  /// Whether the callback has run (needed for INI parsing)
4445  /// Specify that extra args beyond type_size_max should be allowed
4446  bool allow_extra_args_{false};
4447  /// Specify that the option should act like a flag vs regular option
4448  bool flag_like_{false};
4449  /// Control option to run the callback to set the default
4451  /// flag indicating a separator needs to be injected after each argument call
4452  bool inject_separator_{false};
4453  /// flag indicating that the option should trigger the validation and callback chain on each result when loaded
4454  bool trigger_on_result_{false};
4455  /// flag indicating that the option should force the callback regardless if any results present
4456  bool force_callback_{false};
4457  ///@}
4458 
4459  /// Making an option by hand is not defined, it must be made by the App class
4460  Option(std::string option_name, std::string option_description, callback_t callback, App *parent)
4461  : description_(std::move(option_description)), parent_(parent), callback_(std::move(callback)) {
4462  std::tie(snames_, lnames_, pname_) = detail::get_names(detail::split_names(option_name));
4463  }
4464 
4465  public:
4466  /// @name Basic
4467  ///@{
4468 
4469  Option(const Option &) = delete;
4470  Option &operator=(const Option &) = delete;
4471 
4472  /// Count the total number of times an option was passed
4473  CLI11_NODISCARD std::size_t count() const { return results_.size(); }
4474 
4475  /// True if the option was not passed
4476  CLI11_NODISCARD bool empty() const { return results_.empty(); }
4477 
4478  /// This bool operator returns true if any arguments were passed or the option callback is forced
4479  explicit operator bool() const { return !empty() || force_callback_; }
4480 
4481  /// Clear the parsed results (mostly for testing)
4482  void clear() {
4483  results_.clear();
4485  }
4486 
4487  ///@}
4488  /// @name Setting options
4489  ///@{
4490 
4491  /// Set the number of expected arguments
4492  Option *expected(int value);
4493 
4494  /// Set the range of expected arguments
4495  Option *expected(int value_min, int value_max);
4496 
4497  /// Set the value of allow_extra_args which allows extra value arguments on the flag or option to be included
4498  /// with each instance
4499  Option *allow_extra_args(bool value = true) {
4501  return this;
4502  }
4503  /// Get the current value of allow extra args
4505  /// Set the value of trigger_on_parse which specifies that the option callback should be triggered on every parse
4506  Option *trigger_on_parse(bool value = true) {
4508  return this;
4509  }
4510  /// The status of trigger on parse
4512 
4513  /// Set the value of force_callback
4514  Option *force_callback(bool value = true) {
4516  return this;
4517  }
4518  /// The status of force_callback
4520 
4521  /// Set the value of run_callback_for_default which controls whether the callback function should be called to set
4522  /// the default This is controlled automatically but could be manipulated by the user.
4523  Option *run_callback_for_default(bool value = true) {
4525  return this;
4526  }
4527  /// Get the current value of run_callback_for_default
4529 
4530  /// Adds a Validator with a built in type name
4531  Option *check(Validator validator, const std::string &validator_name = "");
4532 
4533  /// Adds a Validator. Takes a const string& and returns an error message (empty if conversion/check is okay).
4534  Option *check(std::function<std::string(const std::string &)> Validator,
4535  std::string Validator_description = "",
4536  std::string Validator_name = "");
4537 
4538  /// Adds a transforming Validator with a built in type name
4539  Option *transform(Validator Validator, const std::string &Validator_name = "");
4540 
4541  /// Adds a Validator-like function that can change result
4542  Option *transform(const std::function<std::string(std::string)> &func,
4543  std::string transform_description = "",
4544  std::string transform_name = "");
4545 
4546  /// Adds a user supplied function to run on each item passed in (communicate though lambda capture)
4547  Option *each(const std::function<void(std::string)> &func);
4548 
4549  /// Get a named Validator
4550  Validator *get_validator(const std::string &Validator_name = "");
4551 
4552  /// Get a Validator by index NOTE: this may not be the order of definition
4554 
4555  /// Sets required options
4557  if(opt != this) {
4558  needs_.insert(opt);
4559  }
4560  return this;
4561  }
4562 
4563  /// Can find a string if needed
4564  template <typename T = App> Option *needs(std::string opt_name) {
4565  auto opt = static_cast<T *>(parent_)->get_option_no_throw(opt_name);
4566  if(opt == nullptr) {
4567  throw IncorrectConstruction::MissingOption(opt_name);
4568  }
4569  return needs(opt);
4570  }
4571 
4572  /// Any number supported, any mix of string and Opt
4573  template <typename A, typename B, typename... ARG> Option *needs(A opt, B opt1, ARG... args) {
4574  needs(opt);
4575  return needs(opt1, args...); // NOLINT(readability-suspicious-call-argument)
4576  }
4577 
4578  /// Remove needs link from an option. Returns true if the option really was in the needs list.
4579  bool remove_needs(Option *opt);
4580 
4581  /// Sets excluded options
4582  Option *excludes(Option *opt);
4583 
4584  /// Can find a string if needed
4585  template <typename T = App> Option *excludes(std::string opt_name) {
4586  auto opt = static_cast<T *>(parent_)->get_option_no_throw(opt_name);
4587  if(opt == nullptr) {
4588  throw IncorrectConstruction::MissingOption(opt_name);
4589  }
4590  return excludes(opt);
4591  }
4592 
4593  /// Any number supported, any mix of string and Opt
4594  template <typename A, typename B, typename... ARG> Option *excludes(A opt, B opt1, ARG... args) {
4595  excludes(opt);
4596  return excludes(opt1, args...);
4597  }
4598 
4599  /// Remove needs link from an option. Returns true if the option really was in the needs list.
4600  bool remove_excludes(Option *opt);
4601 
4602  /// Sets environment variable to read if no option given
4604  envname_ = std::move(name);
4605  return this;
4606  }
4607 
4608  /// Ignore case
4609  ///
4610  /// The template hides the fact that we don't have the definition of App yet.
4611  /// You are never expected to add an argument to the template here.
4612  template <typename T = App> Option *ignore_case(bool value = true);
4613 
4614  /// Ignore underscores in the option names
4615  ///
4616  /// The template hides the fact that we don't have the definition of App yet.
4617  /// You are never expected to add an argument to the template here.
4618  template <typename T = App> Option *ignore_underscore(bool value = true);
4619 
4620  /// Take the last argument if given multiple times (or another policy)
4622 
4623  /// Disable flag overrides values, e.g. --flag=<value> is not allowed
4624  Option *disable_flag_override(bool value = true) {
4626  return this;
4627  }
4628  ///@}
4629  /// @name Accessors
4630  ///@{
4631 
4632  /// The number of arguments the option expects
4634 
4635  /// The minimum number of arguments the option expects
4637  /// The maximum number of arguments the option expects
4639 
4640  /// Return the inject_separator flag
4642 
4643  /// The environment variable associated to this value
4645 
4646  /// The set of options needed
4647  CLI11_NODISCARD std::set<Option *> get_needs() const { return needs_; }
4648 
4649  /// The set of options excluded
4650  CLI11_NODISCARD std::set<Option *> get_excludes() const { return excludes_; }
4651 
4652  /// The default value (for help printing)
4654 
4655  /// Get the callback function
4657 
4658  /// Get the long names
4659  CLI11_NODISCARD const std::vector<std::string> &get_lnames() const { return lnames_; }
4660 
4661  /// Get the short names
4662  CLI11_NODISCARD const std::vector<std::string> &get_snames() const { return snames_; }
4663 
4664  /// Get the flag names with specified default values
4665  CLI11_NODISCARD const std::vector<std::string> &get_fnames() const { return fnames_; }
4666  /// Get a single name for the option, first of lname, pname, sname, envname
4668  if(!lnames_.empty()) {
4669  return lnames_[0];
4670  }
4671  if(!pname_.empty()) {
4672  return pname_;
4673  }
4674  if(!snames_.empty()) {
4675  return snames_[0];
4676  }
4677  return envname_;
4678  }
4679  /// The number of times the option expects to be included
4681 
4682  /// The number of times the option expects to be included
4684  /// The max number of times the option expects to be included
4686 
4687  /// The total min number of expected string values to be used
4689 
4690  /// Get the maximum number of items expected to be returned and used for the callback