25#include "llvm/ADT/STLExtras.h"
34 :
public llvm::ErrorInfo<OptionParseError, DiagnosticError> {
40 : ErrorInfo(std::error_code(EINVAL, std::generic_category())),
43 : ErrorInfo(std::error_code(EINVAL, std::generic_category())) {
45 if (
auto pos = arg.
GetPos()) {
46 uint16_t len = arg.GetLength();
47 sloc = {FileSpec{}, 1, *pos, len, false, true};
51 std::unique_ptr<CloneableError>
Clone()
const override {
52 return std::make_unique<OptionParseError>(
m_details[0]);
54 llvm::ArrayRef<DiagnosticDetail>
GetDetails()
const override {
85 bool is_a_subset =
true;
86 OptionSet::const_iterator pos_a;
87 OptionSet::const_iterator pos_b;
92 for (pos_a = set_a.begin(); pos_a != set_a.end() && is_a_subset; ++pos_a) {
93 pos_b = set_b.find(*pos_a);
94 if (pos_b == set_b.end())
106 size_t num_diffs = 0;
107 OptionSet::const_iterator pos_a;
108 OptionSet::const_iterator pos_b;
110 for (pos_a = set_a.begin(); pos_a != set_a.end(); ++pos_a) {
111 pos_b = set_b.find(*pos_a);
112 if (pos_b == set_b.end()) {
114 diffs.insert(*pos_a);
126 OptionSet::const_iterator pos;
127 OptionSet::iterator pos_union;
131 for (pos = set_a.begin(); pos != set_a.end(); ++pos)
132 union_set.insert(*pos);
135 for (pos = set_b.begin(); pos != set_b.end(); ++pos) {
136 pos_union = union_set.find(*pos);
137 if (pos_union == union_set.end())
138 union_set.insert(*pos);
152 if (num_options == 0)
162 uint32_t num_option_sets = 0;
164 for (
const auto &def : opt_defs) {
165 uint32_t this_usage_mask = def.usage_mask;
167 if (num_option_sets == 0)
171 if (this_usage_mask & (1 << j)) {
172 if (num_option_sets <= j)
173 num_option_sets = j + 1;
179 if (num_option_sets > 0) {
183 for (
const auto &def : opt_defs) {
184 for (uint32_t j = 0; j < num_option_sets; j++) {
185 if (def.usage_mask & 1 << j) {
205 std::map<int, uint32_t> option_seen;
208 for (
size_t i = 0; i < defs.size(); ++i) {
209 const int short_opt = defs[i].short_option;
215 auto [pos, inserted] = option_seen.try_emplace(short_opt, i);
216 if (!inserted && short_opt) {
219 if (defs[i].HasShortOption())
222 "option[{0}] --{1} has a short option -{2} that "
223 "conflicts with option[{3}] --{4}, short option won't "
225 i, defs[i].long_option, short_opt, pos->second,
232 "option[{0}] --{1} has a short option {2:x} that "
233 "conflicts with option[{3}] --{4}, short option won't "
235 (
int)i, defs[i].long_option, short_opt, pos->second,
265 uint32_t output_max_columns,
267 std::string actual_text;
272 actual_text.append(condition);
273 actual_text.append(
"] ");
282 if (
static_cast<uint32_t
>(visible_length + strm.
GetIndentLevel()) <
283 output_max_columns) {
293 int final_end = visible_length;
296 while (end < final_end) {
299 while ((start < final_end) && (actual_text[start] ==
' '))
302 end = start + text_width;
308 while (end > start && actual_text[end] !=
' ' &&
309 actual_text[end] !=
'\t' && actual_text[end] !=
'\n')
313 sub_len = end - start;
317 assert(start < final_end);
318 assert(start + sub_len <= final_end);
320 llvm::StringRef(actual_text.c_str() + start, sub_len), use_color));
328 if (!long_option || !long_option[0])
332 if (opt_defs.empty())
335 const char *long_option_name = long_option;
336 if (long_option[0] ==
'-' && long_option[1] ==
'-')
337 long_option_name += 2;
339 for (
auto &def : opt_defs) {
340 if (!def.long_option)
343 if (strcmp(def.long_option, long_option_name) == 0)
358 const char *footer,
bool show_optional,
Stream &strm) {
362 if (header && header[0])
365 if (show_optional && !opt_def.
required)
367 const bool show_short_option =
369 if (show_short_option)
381 strm.
Printf(
"%s[<%s>]", show_short_option ?
"" :
"=",
385 if (show_optional && !opt_def.
required)
387 if (footer && footer[0])
393 uint32_t screen_width,
bool use_color) {
401 if (num_options == 0)
405 if (!only_print_args)
406 strm.
PutCString(
"\nCommand Options Usage:\n");
416 if (!only_print_args) {
418 for (uint32_t opt_set = 0; opt_set < num_option_sets; ++opt_set) {
425 uint32_t opt_set_mask = 1 << opt_set;
433 std::set<int> required_options;
434 std::set<int> optional_options;
436 for (
auto &def : opt_defs) {
437 if (def.usage_mask & opt_set_mask && def.HasShortOption() &&
440 required_options.insert(def.short_option);
442 optional_options.insert(def.short_option);
447 if (!required_options.empty()) {
449 for (
int short_option : required_options)
453 if (!optional_options.empty()) {
455 for (
int short_option : optional_options)
461 for (
auto &def : opt_defs) {
462 if (def.usage_mask & opt_set_mask && def.HasShortOption() &&
468 for (
auto &def : opt_defs) {
469 if (def.usage_mask & opt_set_mask && !def.required &&
484 if (!only_print_args)
487 strm <<
" " << arguments_str.
GetString();
490 if (!only_print_args) {
502 std::multimap<int, uint32_t> options_ordered;
503 for (
auto def : llvm::enumerate(opt_defs))
504 options_ordered.insert(
505 std::make_pair(def.value().short_option, def.index()));
510 bool first_option_printed =
false;
512 for (
auto pos : options_ordered) {
514 if (first_option_printed)
517 first_option_printed =
true;
539 bool is_first =
true;
540 for (
const auto &enum_value : opt_def.
enum_values) {
542 strm.
Printf(
"%s", enum_value.string_value);
546 strm.
Printf(
" | %s", enum_value.string_value);
559 bool options_are_valid =
false;
563 for (
int i = 0; i < num_levels && !options_are_valid; ++i) {
582 options_are_valid =
true;
586 options_are_valid =
true;
589 if (!options_are_valid)
590 return llvm::createStringError(
591 "invalid combination of options for the given command");
593 return llvm::Error::success();
602 bool options_are_valid =
false;
606 for (
int i = 0; i < num_levels && !options_are_valid; ++i) {
614 options_are_valid =
true;
618 if (!options_are_valid)
619 return llvm::createStringError(
620 "invalid combination of options for the given command");
622 return llvm::Error::success();
638 for (
size_t i = 0; i < opt_element_vector.size(); i++) {
639 size_t opt_pos =
static_cast<size_t>(opt_element_vector[i].opt_pos);
640 size_t opt_arg_pos =
static_cast<size_t>(opt_element_vector[i].opt_arg_pos);
641 int opt_defs_index = opt_element_vector[i].opt_defs_index;
650 std::string opt_str =
"-a";
652 for (
auto &def : opt_defs) {
653 if (!def.short_option)
655 opt_str[1] = def.short_option;
657 def.usage_text, use_color));
662 std::string full_name(
"--");
663 for (
auto &def : opt_defs) {
664 if (!def.short_option)
667 full_name.erase(full_name.begin() + 2, full_name.end());
668 full_name.append(def.long_option);
670 def.usage_text, use_color));
680 if (cur_opt_str.starts_with(
"--") && cur_opt_str != long_option) {
682 "--" + long_option.str(),
695 if (cur_opt_str.consume_front(
"--")) {
696 for (
auto &def : opt_defs) {
697 llvm::StringRef long_option(def.long_option);
698 if (long_option.starts_with(cur_opt_str))
700 "--" + long_option.str(),
712 if (opt_defs_index != -1) {
733 std::unique_ptr<SearchFilter> filter_up;
735 int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
738 const auto &enum_values = opt_defs[opt_defs_index].enum_values;
739 if (!enum_values.empty())
740 for (
const auto &enum_value : enum_values)
749 uint32_t completion_mask = opt_defs[opt_defs_index].completion_type;
751 if (completion_mask == 0) {
753 opt_defs[opt_defs_index].argument_type;
757 opt_defs[opt_defs_index].argument_type);
765 for (
size_t i = 0; i < opt_element_vector.size(); i++) {
766 int cur_defs_index = opt_element_vector[i].opt_defs_index;
774 int cur_arg_pos = opt_element_vector[i].opt_arg_pos;
775 const char *cur_opt_name = opt_defs[cur_defs_index].long_option;
779 if (cur_opt_name && strcmp(cur_opt_name,
"shlib") == 0 &&
781 const char *module_name =
790 std::make_unique<SearchFilterByModule>(target_sp, module_spec);
798 interpreter, completion_mask, request, filter_up.get());
803 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
821 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
822 if (group_option_defs[i].usage_mask & src_mask) {
831 OptionGroup *group, llvm::ArrayRef<llvm::StringRef> exclude_long_options) {
833 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
834 const auto &definition = group_option_defs[i];
835 if (llvm::is_contained(exclude_long_options, definition.long_option))
848 llvm::StringRef option_value,
868 std::set<OptionGroup *> group_set;
872 if (group_set.find(group) == group_set.end()) {
874 group_set.insert(group);
880 std::set<OptionGroup *> group_set;
885 if (group_set.find(group) == group_set.end()) {
887 group_set.insert(group);
900 std::vector<char *> result;
902 result.push_back(
const_cast<char *
>(
"<FAKE-ARG0>"));
904 result.push_back(
const_cast<char *
>(entry.c_str()));
905 result.push_back(
nullptr);
911 const Args &original) {
912 return llvm::find_if(
924 const Args &original) {
926 for (
const char *arg : parsed) {
928 assert(pos != original.
end());
935 const Option &long_option) {
936 std::string short_opt = llvm::formatv(
"-{0}",
char(long_option.
val)).str();
937 std::string long_opt =
939 for (
const auto &entry : llvm::enumerate(args)) {
940 if (entry.value().ref().starts_with(short_opt) ||
941 entry.value().ref().starts_with(long_opt))
942 return entry.index();
950 llvm::raw_string_ostream sstr(storage);
956 for (
size_t i = 0; long_options[i].
definition !=
nullptr; ++i) {
957 if (long_options[i].flag ==
nullptr) {
958 sstr << (char)long_options[i].val;
959 switch (long_options[i].definition->option_has_arg) {
977 std::string &input_line) {
980 if (long_options ==
nullptr) {
981 return llvm::createStringError(
"Invalid long options");
986 Args args_copy = args;
989 std::unique_lock<std::mutex> lock;
993 int long_options_index = -1;
995 &long_options_index);
998 return llvm::createStringError(llvm::inconvertibleErrorCode(),
999 "last option requires an argument");
1006 return llvm::createStringError(
"Unknown or ambiguous option");
1015 if (long_options_index == -1) {
1016 for (
int j = 0; long_options[j].
definition || long_options[j].
flag ||
1017 long_options[j].
val;
1019 if (long_options[j].val == val) {
1020 long_options_index = j;
1027 if (long_options_index == -1) {
1028 return llvm::createStringError(
1029 llvm::formatv(
"Invalid option with value '{0}'.",
char(val)).str());
1033 option_str.
Printf(
"-%c", val);
1038 const char *option_arg =
nullptr;
1042 return llvm::createStringError(
1043 llvm::formatv(
"Option '{0}' is missing argument specifier.",
1054 return llvm::createStringError(
1055 llvm::formatv(
"error with options table; invalid value in has_arg "
1056 "field for option '{0}'.",
1069 std::string option_to_insert;
1071 if (idx !=
size_t(-1) && has_arg) {
1072 bool arg_has_backtick = args_copy[idx + 1].GetQuoteChar() ==
'`';
1073 if (arg_has_backtick)
1074 option_to_insert =
"`";
1075 option_to_insert += option_arg;
1076 if (arg_has_backtick)
1077 option_to_insert +=
"`";
1079 option_to_insert = option_arg;
1083 option_arg_vector->emplace_back(std::string(option_str.
GetString()),
1084 has_arg, option_to_insert);
1086 if (idx ==
size_t(-1))
1089 if (!input_line.empty()) {
1090 llvm::StringRef tmp_arg = args_copy[idx].ref();
1091 size_t pos = input_line.find(tmp_arg);
1092 if (pos != std::string::npos)
1093 input_line.erase(pos, tmp_arg.size());
1100 if (input_line.size() > 0) {
1101 size_t pos = input_line.find(option_to_insert);
1102 if (pos != std::string::npos)
1103 input_line.erase(pos, option_to_insert.size());
1109 return std::move(args_copy);
1113 uint32_t cursor_index) {
1116 option_element_vector.clear();
1118 if (long_options ==
nullptr)
1119 return option_element_vector;
1123 std::unique_lock<std::mutex> lock;
1132 bool failed_once =
false;
1133 uint32_t dash_dash_pos = -1;
1136 bool missing_argument =
false;
1137 int long_options_index = -1;
1140 &long_options_index);
1166 if (dash_dash_pos == cursor_index) {
1167 option_element_vector.push_back(
1175 }
else if (val ==
'?') {
1182 }
else if (val == 0) {
1184 }
else if (val ==
':') {
1187 missing_argument =
true;
1193 if (long_options_index == -1) {
1194 for (
int j = 0; long_options[j].
definition || long_options[j].
flag ||
1195 long_options[j].
val;
1197 if (long_options[j].val == val) {
1198 long_options_index = j;
1205 if (long_options_index >= 0) {
1206 int opt_defs_index = -1;
1207 for (
size_t i = 0; i < opt_defs.size(); i++) {
1208 if (opt_defs[i].short_option != val)
1228 if (missing_argument)
1280 if ((
static_cast<int32_t
>(dash_dash_pos) == -1 ||
1281 cursor_index < dash_dash_pos) &&
1283 option_element_vector.push_back(
1287 return option_element_vector;
1293 bool require_validation) {
1296 if (long_options ==
nullptr) {
1297 return llvm::createStringError(
"invalid long options");
1303 std::unique_lock<std::mutex> lock;
1306 int long_options_index = -1;
1308 &long_options_index);
1324 args[idx],
"unknown or ambiguous option"));
1337 if (long_options_index == -1) {
1338 for (
int i = 0; long_options[i].
definition || long_options[i].
flag ||
1339 long_options[i].
val;
1341 if (long_options[i].val == val) {
1342 long_options_index = i;
1348 if (long_options_index >= 0 &&
1349 long_options[long_options_index].definition) {
1357 platform_sp = target_sp ? target_sp->GetPlatform() :
PlatformSP();
1361 if (!platform_sp && require_validation) {
1364 return llvm::createStringError(
1365 "cannot validate options: no platform available");
1368 bool validation_failed =
false;
1373 execution_context ? execution_context : &dummy_context;
1375 validation_failed =
true;
1383 if (!validation_failed)
1396 "invalid option with value '%i'", val);
1401 return error.ToError();
1409 llvm::StringRef option_arg,
const char short_option,
1410 llvm::StringRef long_option, llvm::StringRef additional_context) {
1412 llvm::raw_string_ostream stream(buffer);
1413 stream <<
"Invalid value ('" << option_arg <<
"') for -" << short_option;
1414 if (!long_option.empty())
1415 stream <<
" (" << long_option <<
")";
1416 if (!additional_context.empty())
1417 stream <<
": " << additional_context;
1418 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 size_t FindArgumentIndexForOption(const Args &args, const Option &long_option)
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.
std::string FormatAnsiTerminalCodes(llvm::StringRef format, bool do_color=true)
size_t ColumnWidth(llvm::StringRef str)
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