27#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/Support/ErrorExtras.h"
38 :
public llvm::ErrorInfo<OptionParseError, DiagnosticError> {
44 : ErrorInfo(std::error_code(EINVAL, std::generic_category())),
47 : ErrorInfo(std::error_code(EINVAL, std::generic_category())) {
49 if (
auto pos = arg.
GetPos()) {
50 uint16_t len = arg.GetLength();
51 sloc = {FileSpec{}, 1, *pos, len, false, true};
55 std::unique_ptr<CloneableError>
Clone()
const override {
56 return std::make_unique<OptionParseError>(
m_details[0]);
58 llvm::ArrayRef<DiagnosticDetail>
GetDetails()
const override {
89 bool is_a_subset =
true;
90 OptionSet::const_iterator pos_a;
91 OptionSet::const_iterator pos_b;
96 for (pos_a = set_a.begin(); pos_a != set_a.end() && is_a_subset; ++pos_a) {
97 pos_b = set_b.find(*pos_a);
98 if (pos_b == set_b.end())
110 size_t num_diffs = 0;
111 OptionSet::const_iterator pos_a;
112 OptionSet::const_iterator pos_b;
114 for (pos_a = set_a.begin(); pos_a != set_a.end(); ++pos_a) {
115 pos_b = set_b.find(*pos_a);
116 if (pos_b == set_b.end()) {
118 diffs.insert(*pos_a);
130 OptionSet::const_iterator pos;
131 OptionSet::iterator pos_union;
135 for (pos = set_a.begin(); pos != set_a.end(); ++pos)
136 union_set.insert(*pos);
139 for (pos = set_b.begin(); pos != set_b.end(); ++pos) {
140 pos_union = union_set.find(*pos);
141 if (pos_union == union_set.end())
142 union_set.insert(*pos);
156 if (num_options == 0)
166 uint32_t num_option_sets = 0;
168 for (
const auto &def : opt_defs) {
169 uint32_t this_usage_mask = def.usage_mask;
171 if (num_option_sets == 0)
175 if (this_usage_mask & (1 << j)) {
176 if (num_option_sets <= j)
177 num_option_sets = j + 1;
183 if (num_option_sets > 0) {
187 for (
const auto &def : opt_defs) {
188 for (uint32_t j = 0; j < num_option_sets; j++) {
189 if (def.usage_mask & 1 << j) {
209 std::map<int, uint32_t> option_seen;
212 for (
size_t i = 0; i < defs.size(); ++i) {
213 const int short_opt = defs[i].short_option;
219 auto [pos, inserted] = option_seen.try_emplace(short_opt, i);
220 if (!inserted && short_opt) {
223 if (defs[i].HasShortOption())
226 "option[{0}] --{1} has a short option -{2} that "
227 "conflicts with option[{3}] --{4}, short option won't "
229 i, defs[i].long_option, short_opt, pos->second,
236 "option[{0}] --{1} has a short option {2:x} that "
237 "conflicts with option[{3}] --{4}, short option won't "
239 (
int)i, defs[i].long_option, short_opt, pos->second,
269 uint32_t output_max_columns,
271 std::string actual_text;
275 actual_text.append(condition);
276 actual_text.append(
"] ");
287 if (!long_option || !long_option[0])
291 if (opt_defs.empty())
294 const char *long_option_name = long_option;
295 if (long_option[0] ==
'-' && long_option[1] ==
'-')
296 long_option_name += 2;
298 for (
auto &def : opt_defs) {
299 if (!def.long_option)
302 if (strcmp(def.long_option, long_option_name) == 0)
317 const char *footer,
bool show_optional,
Stream &strm) {
321 if (header && header[0])
324 if (show_optional && !opt_def.
required)
326 const bool show_short_option =
328 if (show_short_option)
340 strm.
Printf(
"%s[<%s>]", show_short_option ?
"" :
"=",
344 if (show_optional && !opt_def.
required)
346 if (footer && footer[0])
352 uint32_t screen_width,
bool use_color) {
360 if (num_options == 0)
364 if (!only_print_args)
365 strm.
PutCString(
"\nCommand Options Usage:\n");
375 if (!only_print_args) {
377 for (uint32_t opt_set = 0; opt_set < num_option_sets; ++opt_set) {
384 uint32_t opt_set_mask = 1 << opt_set;
392 std::set<int> required_options;
393 std::set<int> optional_options;
395 for (
auto &def : opt_defs) {
396 if (def.usage_mask & opt_set_mask && def.HasShortOption() &&
399 required_options.insert(def.short_option);
401 optional_options.insert(def.short_option);
406 if (!required_options.empty()) {
408 for (
int short_option : required_options)
412 if (!optional_options.empty()) {
414 for (
int short_option : optional_options)
420 for (
auto &def : opt_defs) {
421 if (def.usage_mask & opt_set_mask && def.HasShortOption() &&
427 for (
auto &def : opt_defs) {
428 if (def.usage_mask & opt_set_mask && !def.required &&
443 if (!only_print_args)
446 strm <<
" " << arguments_str.
GetString();
449 if (!only_print_args) {
461 std::multimap<int, uint32_t> options_ordered;
462 for (
auto def : llvm::enumerate(opt_defs))
463 options_ordered.insert(
464 std::make_pair(def.value().short_option, def.index()));
469 bool first_option_printed =
false;
471 for (
auto pos : options_ordered) {
473 if (first_option_printed)
476 first_option_printed =
true;
498 bool is_first =
true;
499 for (
const auto &enum_value : opt_def.
enum_values) {
501 strm.
Printf(
"%s", enum_value.string_value);
505 strm.
Printf(
" | %s", enum_value.string_value);
518 bool options_are_valid =
false;
522 for (
int i = 0; i < num_levels && !options_are_valid; ++i) {
541 options_are_valid =
true;
545 options_are_valid =
true;
548 if (!options_are_valid)
549 return llvm::createStringError(
550 "invalid combination of options for the given command");
552 return llvm::Error::success();
561 bool options_are_valid =
false;
565 for (
int i = 0; i < num_levels && !options_are_valid; ++i) {
573 options_are_valid =
true;
577 if (!options_are_valid)
578 return llvm::createStringError(
579 "invalid combination of options for the given command");
581 return llvm::Error::success();
597 for (
size_t i = 0; i < opt_element_vector.size(); i++) {
598 size_t opt_pos =
static_cast<size_t>(opt_element_vector[i].opt_pos);
599 size_t opt_arg_pos =
static_cast<size_t>(opt_element_vector[i].opt_arg_pos);
600 int opt_defs_index = opt_element_vector[i].opt_defs_index;
609 std::string opt_str =
"-a";
611 for (
auto &def : opt_defs) {
612 if (!def.short_option)
614 opt_str[1] = def.short_option;
616 def.usage_text, use_color));
621 std::string full_name(
"--");
622 for (
auto &def : opt_defs) {
623 if (!def.short_option)
626 full_name.erase(full_name.begin() + 2, full_name.end());
627 full_name.append(def.long_option);
629 def.usage_text, use_color));
639 if (cur_opt_str.starts_with(
"--") && cur_opt_str != long_option) {
641 "--" + long_option.str(),
654 if (cur_opt_str.consume_front(
"--")) {
655 for (
auto &def : opt_defs) {
656 llvm::StringRef long_option(def.long_option);
657 if (long_option.starts_with(cur_opt_str))
659 "--" + long_option.str(),
671 if (opt_defs_index != -1) {
692 std::unique_ptr<SearchFilter> filter_up;
694 int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
697 const auto &enum_values = opt_defs[opt_defs_index].enum_values;
698 if (!enum_values.empty())
699 for (
const auto &enum_value : enum_values)
708 uint32_t completion_mask = opt_defs[opt_defs_index].completion_type;
710 if (completion_mask == 0) {
712 opt_defs[opt_defs_index].argument_type;
716 opt_defs[opt_defs_index].argument_type);
724 for (
size_t i = 0; i < opt_element_vector.size(); i++) {
725 int cur_defs_index = opt_element_vector[i].opt_defs_index;
733 int cur_arg_pos = opt_element_vector[i].opt_arg_pos;
734 const char *cur_opt_name = opt_defs[cur_defs_index].long_option;
738 if (cur_opt_name && strcmp(cur_opt_name,
"shlib") == 0 &&
740 const char *module_name =
749 std::make_unique<SearchFilterByModule>(target_sp, module_spec);
757 interpreter, completion_mask, request, filter_up.get());
762 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
780 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
781 if (group_option_defs[i].usage_mask & src_mask) {
790 OptionGroup *group, llvm::ArrayRef<llvm::StringRef> exclude_long_options) {
792 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
793 const auto &definition = group_option_defs[i];
794 if (llvm::is_contained(exclude_long_options, definition.long_option))
807 llvm::StringRef option_value,
827 std::set<OptionGroup *> group_set;
831 if (group_set.find(group) == group_set.end()) {
833 group_set.insert(group);
839 std::set<OptionGroup *> group_set;
844 if (group_set.find(group) == group_set.end()) {
846 group_set.insert(group);
859 std::vector<char *> result;
861 result.push_back(
const_cast<char *
>(
"<FAKE-ARG0>"));
863 result.push_back(
const_cast<char *
>(entry.c_str()));
864 result.push_back(
nullptr);
870 const Args &original) {
871 return llvm::find_if(
883 const Args &original) {
885 for (
const char *arg : parsed) {
887 assert(pos != original.
end());
896static std::pair<size_t, size_t>
898 std::string short_opt = llvm::formatv(
"-{0}",
char(long_option.
val)).str();
899 std::string long_opt =
901 for (
const auto &entry : llvm::enumerate(args)) {
902 llvm::StringRef arg = entry.value().ref();
903 size_t idx = entry.index();
907 if (arg == short_opt || arg.starts_with(long_opt))
909 else if (arg.starts_with(short_opt))
911 return {idx, val_idx};
919 llvm::raw_string_ostream sstr(storage);
925 for (
size_t i = 0; long_options[i].
definition !=
nullptr; ++i) {
926 if (long_options[i].flag ==
nullptr) {
927 sstr << (char)long_options[i].val;
928 switch (long_options[i].definition->option_has_arg) {
946 std::string &input_line) {
949 if (long_options ==
nullptr) {
950 return llvm::createStringError(
"invalid long options");
955 Args args_copy = args;
958 std::unique_lock<std::mutex> lock;
962 int long_options_index = -1;
964 &long_options_index);
967 return llvm::createStringError(llvm::inconvertibleErrorCode(),
968 "last option requires an argument");
975 return llvm::createStringError(
"unknown or ambiguous option");
984 if (long_options_index == -1) {
985 for (
int j = 0; long_options[j].
definition || long_options[j].
flag ||
988 if (long_options[j].val == val) {
989 long_options_index = j;
996 if (long_options_index == -1) {
997 return llvm::createStringErrorV(
"invalid option with value '{0}'",
1002 option_str.
Printf(
"-%c", val);
1003 const Option &opt = long_options[long_options_index];
1006 const char *option_arg =
nullptr;
1010 return llvm::createStringError(
1011 llvm::formatv(
"Option '{0}' is missing argument specifier.",
1022 return llvm::createStringError(
1023 llvm::formatv(
"error with options table; invalid value in has_arg "
1024 "field for option '{0}'.",
1036 std::string option_to_insert;
1039 bool arg_has_backtick = args_copy[val_idx].GetQuoteChar() ==
'`';
1040 if (arg_has_backtick)
1041 option_to_insert =
"`";
1042 option_to_insert += option_arg;
1043 if (arg_has_backtick)
1044 option_to_insert +=
"`";
1046 option_to_insert = option_arg;
1050 option_arg_vector->emplace_back(std::string(option_str.
GetString()),
1051 has_arg, option_to_insert);
1056 if (!input_line.empty()) {
1057 llvm::StringRef tmp_arg = args_copy[idx].ref();
1058 size_t pos = input_line.find(tmp_arg);
1059 if (pos != std::string::npos)
1060 input_line.erase(pos, tmp_arg.size());
1067 if (input_line.size() > 0) {
1068 size_t pos = input_line.find(option_to_insert);
1069 if (pos != std::string::npos)
1070 input_line.erase(pos, option_to_insert.size());
1076 return std::move(args_copy);
1080 uint32_t cursor_index) {
1083 option_element_vector.clear();
1085 if (long_options ==
nullptr)
1086 return option_element_vector;
1090 std::unique_lock<std::mutex> lock;
1099 bool failed_once =
false;
1100 uint32_t dash_dash_pos = -1;
1103 bool missing_argument =
false;
1104 int long_options_index = -1;
1107 &long_options_index);
1133 if (dash_dash_pos == cursor_index) {
1134 option_element_vector.push_back(
1142 }
else if (val ==
'?') {
1149 }
else if (val == 0) {
1151 }
else if (val ==
':') {
1154 missing_argument =
true;
1160 if (long_options_index == -1) {
1161 for (
int j = 0; long_options[j].
definition || long_options[j].
flag ||
1162 long_options[j].
val;
1164 if (long_options[j].val == val) {
1165 long_options_index = j;
1172 if (long_options_index >= 0) {
1173 int opt_defs_index = -1;
1174 for (
size_t i = 0; i < opt_defs.size(); i++) {
1175 if (opt_defs[i].short_option != val)
1195 if (missing_argument)
1247 if ((
static_cast<int32_t
>(dash_dash_pos) == -1 ||
1248 cursor_index < dash_dash_pos) &&
1250 option_element_vector.push_back(
1254 return option_element_vector;
1260 bool require_validation) {
1263 if (long_options ==
nullptr) {
1264 return llvm::createStringError(
"invalid long options");
1270 std::unique_lock<std::mutex> lock;
1273 int long_options_index = -1;
1275 &long_options_index);
1291 args[idx],
"unknown or ambiguous option"));
1304 if (long_options_index == -1) {
1305 for (
int i = 0; long_options[i].
definition || long_options[i].
flag ||
1306 long_options[i].
val;
1308 if (long_options[i].val == val) {
1309 long_options_index = i;
1315 if (long_options_index >= 0 &&
1316 long_options[long_options_index].definition) {
1324 platform_sp = target_sp ? target_sp->GetPlatform() :
PlatformSP();
1328 if (!platform_sp && require_validation) {
1331 return llvm::createStringError(
1332 "cannot validate options: no platform available");
1335 bool validation_failed =
false;
1340 execution_context ? execution_context : &dummy_context;
1342 validation_failed =
true;
1350 if (!validation_failed)
1363 "invalid option with value '%i'", val);
1368 return error.ToError();
1376 llvm::StringRef option_arg,
const char short_option,
1377 llvm::StringRef long_option, llvm::StringRef additional_context) {
1379 llvm::raw_string_ostream stream(buffer);
1380 stream <<
"invalid value ('" << option_arg <<
"')";
1382 stream <<
" for -" << short_option;
1383 if (!long_option.empty())
1384 stream <<
" (" << long_option <<
")";
1385 if (!additional_context.empty())
1386 stream <<
": " << additional_context;
1387 return llvm::createStringError(llvm::inconvertibleErrorCode(), buffer);
static llvm::raw_ostream & error(Stream &strm)
static Args ReconstituteArgsAfterParsing(llvm::ArrayRef< char * > parsed, const Args &original)
static std::string BuildShortOptions(const Option *long_options)
static std::vector< char * > GetArgvForParsing(const Args &args)
static bool PrintOption(const OptionDefinition &opt_def, OptionDisplayType display_type, const char *header, const char *footer, bool show_optional, Stream &strm)
static Args::const_iterator FindOriginalIter(const char *arg, const Args &original)
static std::pair< size_t, size_t > FindArgumentIndexForOption(const Args &args, const Option &long_option)
Find the index of the given option in the arguments.
static size_t FindOriginalIndex(const char *arg, const Args &original)
A command line argument class.
std::vector< ArgEntry >::const_iterator const_iterator
void DeleteArgumentAtIndex(size_t idx)
Deletes the argument value at index if idx is a valid argument index.
const_iterator begin() const
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
const_iterator end() const
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
static bool InvokeCommonCompletionCallbacks(CommandInterpreter &interpreter, uint32_t completion_mask, lldb_private::CompletionRequest &request, SearchFilter *searcher)
static const char * g_no_argument
virtual bool WantsRawCommandString()=0
static const ArgumentTableEntry * FindArgumentDataByType(lldb::CommandArgumentType arg_type)
llvm::StringRef GetCommandName() const
void GetFormattedCommandArguments(Stream &str, uint32_t opt_set_mask=LLDB_OPT_SET_ALL)
virtual bool IsDashDashCommand()
static const char * GetArgumentName(lldb::CommandArgumentType arg_type)
"lldb/Utility/ArgCompletionRequest.h"
void AddCompletion(llvm::StringRef completion, llvm::StringRef description="", CompletionMode mode=CompletionMode::Normal)
Adds a possible completion string.
const Args & GetParsedLine() const
llvm::StringRef GetCursorArgumentPrefix() const
void TryCompleteCurrentArg(llvm::StringRef completion, llvm::StringRef description="")
Adds a possible completion string if the completion would complete the current argument.
size_t GetCursorIndex() const
lldb::TargetSP GetSelectedTarget()
static void ReportError(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report error events.
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
void OptionParsingStarting(ExecutionContext *execution_context) override
std::vector< OptionDefinition > m_option_defs
const OptionGroup * GetGroupWithOption(char short_opt)
OptionInfos m_option_infos
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
Status OptionParsingFinished(ExecutionContext *execution_context) override
void Append(OptionGroup *group)
Append options from a OptionGroup class.
virtual Status OptionParsingFinished(ExecutionContext *execution_context)
virtual llvm::ArrayRef< OptionDefinition > GetDefinitions()=0
virtual void OptionParsingStarting(ExecutionContext *execution_context)=0
OptionParseError(DiagnosticDetail detail)
std::vector< DiagnosticDetail > m_details
llvm::ArrayRef< DiagnosticDetail > GetDetails() const override
OptionParseError(const Args::ArgEntry &arg, std::string msg)
std::unique_ptr< CloneableError > Clone() const override
static void Prepare(std::unique_lock< std::mutex > &lock)
static int Parse(llvm::MutableArrayRef< char * > argv, llvm::StringRef optstring, const Option *longopts, int *longindex)
Argv must be an argument vector "as passed to main", i.e.
static int GetOptionIndex()
static char * GetOptionArgument()
static void EnableError(bool error)
static int GetOptionErrorCause()
void OptionsSetUnion(const OptionSet &set_a, const OptionSet &set_b, OptionSet &union_set)
void GenerateOptionUsage(Stream &strm, CommandObject &cmd, uint32_t screen_width, bool use_color)
virtual void HandleOptionArgumentCompletion(lldb_private::CompletionRequest &request, OptionElementVector &opt_element_vector, int opt_element_index, CommandInterpreter &interpreter)
Handles the generic bits of figuring out whether we are in an option, and if so completing it.
llvm::Error VerifyOptions()
virtual Status OptionParsingFinished(ExecutionContext *execution_context)
llvm::Error VerifyPartialOptions()
virtual Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context)=0
Set the value of an option.
uint32_t NumCommandOptions()
virtual void OptionParsingStarting(ExecutionContext *execution_context)=0
void OptionSeen(int short_option)
virtual llvm::ArrayRef< OptionDefinition > GetDefinitions()
Status NotifyOptionParsingFinished(ExecutionContext *execution_context)
Option * GetLongOptions()
Get the option definitions to use when parsing Args options.
OptionSetVector m_optional_options
void NotifyOptionParsingStarting(ExecutionContext *execution_context)
llvm::Expected< Args > ParseAlias(const Args &args, OptionArgVector *option_arg_vector, std::string &input_line)
std::set< int > OptionSet
void OutputFormattedUsageText(Stream &strm, const OptionDefinition &option_def, uint32_t output_max_columns, bool use_color)
OptionSetVector m_required_options
OptionSetVector & GetOptionalOptions()
size_t OptionsSetDiff(const OptionSet &set_a, const OptionSet &set_b, OptionSet &diffs)
void BuildValidOptionSets()
bool HandleOptionCompletion(lldb_private::CompletionRequest &request, OptionElementVector &option_map, CommandInterpreter &interpreter)
Handles the generic bits of figuring out whether we are in an option, and if so completing it.
bool IsASubset(const OptionSet &set_a, const OptionSet &set_b)
bool SupportsLongOption(const char *long_option)
std::vector< Option > m_getopt_table
llvm::Expected< Args > Parse(const Args &args, ExecutionContext *execution_context, lldb::PlatformSP platform_sp, bool require_validation)
Parse the provided arguments.
OptionSetVector & GetRequiredOptions()
OptionElementVector ParseForCompletion(const Args &args, uint32_t cursor_index)
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
static Status FromErrorString(const char *str)
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
void SetIndentLevel(unsigned level)
Set the current indentation level.
size_t EOL()
Output and End of Line character to the stream.
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
void IndentMore(unsigned amount=2)
Increment the current indentation level.
unsigned GetIndentLevel() const
Get the current indentation level.
#define LLDB_MAX_NUM_OPTION_SETS
Option Set definitions.
#define LLDB_INVALID_INDEX64
std::string FormatAnsiTerminalCodes(llvm::StringRef format, bool do_color=true)
void OutputWordWrappedLines(Stream &strm, llvm::StringRef text, uint32_t output_max_columns, bool use_color)
A class that represents a running process on the host machine.
std::vector< OptionArgElement > OptionElementVector
TableValidator< 0 > validator
llvm::Error CreateOptionParsingError(llvm::StringRef option_arg, const char short_option, llvm::StringRef long_option={}, llvm::StringRef additional_context={})
Creates an error that represents the failure to parse an command line option argument.
std::vector< std::tuple< std::string, int, std::string > > OptionArgVector
std::shared_ptr< lldb_private::Platform > PlatformSP
std::shared_ptr< lldb_private::Target > TargetSP
const char * c_str() const
llvm::StringRef ref() const
bool IsQuoted() const
Returns true if this argument was quoted in any way.
std::optional< uint16_t > GetPos() const
Entries in the main argument information table.
lldb::CompletionType completion_type
A source location consisting of a file name and position.
A compiler-independent representation of an lldb_private::Diagnostic.
bool HasShortOption() const
Whether this has a short option character.
OptionValidator * validator
If non-NULL, option is valid iff |validator->IsValid()|, otherwise always valid.
const char * long_option
Full name for this option.
const char * usage_text
Full text explaining what this options does and what (if any) argument to pass it.
bool required
This option is required (in the current usage level).
int option_has_arg
no_argument, required_argument or optional_argument
lldb::CommandArgumentType argument_type
Type of argument this option takes.
OptionEnumValues enum_values
If not empty, an array of enum values.
int short_option
Single character for this option.
virtual const char * LongConditionString() const =0
virtual const char * ShortConditionString() const =0
const OptionDefinition * definition