option_parser.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (C) 2024 Xiaomi Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #ifndef OPTION_PARSER_H_
  6. #define OPTION_PARSER_H_
  7. #include <functional>
  8. #include <string>
  9. #include <vector>
  10. #include "config.h"
  11. namespace analyzer {
  12. class OptionParser
  13. {
  14. public:
  15. enum class HasArgument { No, Yes };
  16. enum class ArgumentCount { One, OneOrMore, ZeroOrMore };
  17. struct Option;
  18. using Callback = std::function<void(const char *)>;
  19. using NullCallback = std::function<void()>;
  20. struct Option {
  21. Option(char short_name, const std::string &long_name,
  22. const std::string &metavar, HasArgument has_argument,
  23. const std::string &help, const Callback &);
  24. char short_name;
  25. std::string long_name;
  26. std::string metavar;
  27. bool has_argument;
  28. std::string help;
  29. Callback callback;
  30. };
  31. struct Argument {
  32. Argument(const std::string &name, ArgumentCount, const Callback &);
  33. std::string name;
  34. ArgumentCount count;
  35. Callback callback;
  36. int handled_count = 0;
  37. };
  38. explicit OptionParser(const char *program_name, const char *description);
  39. void AddOption(const Option &);
  40. void AddOption(char short_name, const char *long_name, const char *help,
  41. const NullCallback &);
  42. void AddOption(const char *long_name, const char *help,
  43. const NullCallback &);
  44. void AddOption(char short_name, const char *long_name, const char *metavar,
  45. const char *help, const Callback &);
  46. void AddArgument(const std::string &name, ArgumentCount, const Callback &);
  47. void SetErrorCallback(const Callback &);
  48. void Parse(int argc, char *argv[]);
  49. void PrintHelp();
  50. private:
  51. static int Match(const char *s, const std::string &full, bool has_argument);
  52. void ANALYZER_PRINTF_FORMAT(2, 3) Errorf(const char *format, ...);
  53. void HandleArgument(size_t *arg_index, const char *arg_value);
  54. void DefaultError(const std::string &);
  55. std::string program_name_;
  56. std::string description_;
  57. std::vector<Option> options_;
  58. std::vector<Argument> arguments_;
  59. Callback on_error_;
  60. };
  61. } // namespace analyzer
  62. #endif