LLDB mainline
Options.cpp
Go to the documentation of this file.
1//===-- Options.cpp -------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
11#include <algorithm>
12#include <bitset>
13#include <map>
14#include <set>
15
22#include "lldb/Target/Target.h"
26#include "lldb/lldb-defines.h"
27#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/Support/ErrorExtras.h"
30
31using namespace lldb;
32using namespace lldb_private;
33
34namespace lldb_private {
35
36/// An llvm::Error that represents an option parsing diagnostic.
38 : public llvm::ErrorInfo<OptionParseError, DiagnosticError> {
39 std::vector<DiagnosticDetail> m_details;
40
41public:
42 using llvm::ErrorInfo<OptionParseError, DiagnosticError>::ErrorInfo;
44 : ErrorInfo(std::error_code(EINVAL, std::generic_category())),
45 m_details({detail}) {}
46 OptionParseError(const Args::ArgEntry &arg, std::string msg)
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};
52 }
53 m_details.push_back(DiagnosticDetail{sloc, lldb::eSeverityError, msg, msg});
54 }
55 std::unique_ptr<CloneableError> Clone() const override {
56 return std::make_unique<OptionParseError>(m_details[0]);
57 }
58 llvm::ArrayRef<DiagnosticDetail> GetDetails() const override {
59 return m_details;
60 }
61 static char ID;
62};
63
65
66} // namespace lldb_private
67
68// Options
70
71Options::~Options() = default;
72
74 m_seen_options.clear();
75 // Let the subclass reset its option values
76 OptionParsingStarting(execution_context);
77}
78
81 return OptionParsingFinished(execution_context);
82}
83
84void Options::OptionSeen(int option_idx) { m_seen_options.insert(option_idx); }
85
86// Returns true is set_a is a subset of set_b; Otherwise returns false.
87
88bool Options::IsASubset(const OptionSet &set_a, const OptionSet &set_b) {
89 bool is_a_subset = true;
90 OptionSet::const_iterator pos_a;
91 OptionSet::const_iterator pos_b;
92
93 // set_a is a subset of set_b if every member of set_a is also a member of
94 // set_b
95
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())
99 is_a_subset = false;
100 }
101
102 return is_a_subset;
103}
104
105// Returns the set difference set_a - set_b, i.e. { x | ElementOf (x, set_a) &&
106// !ElementOf (x, set_b) }
107
108size_t Options::OptionsSetDiff(const OptionSet &set_a, const OptionSet &set_b,
109 OptionSet &diffs) {
110 size_t num_diffs = 0;
111 OptionSet::const_iterator pos_a;
112 OptionSet::const_iterator pos_b;
113
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()) {
117 ++num_diffs;
118 diffs.insert(*pos_a);
119 }
120 }
121
122 return num_diffs;
123}
124
125// Returns the union of set_a and set_b. Does not put duplicate members into
126// the union.
127
128void Options::OptionsSetUnion(const OptionSet &set_a, const OptionSet &set_b,
129 OptionSet &union_set) {
130 OptionSet::const_iterator pos;
131 OptionSet::iterator pos_union;
132
133 // Put all the elements of set_a into the union.
134
135 for (pos = set_a.begin(); pos != set_a.end(); ++pos)
136 union_set.insert(*pos);
137
138 // Put all the elements of set_b that are not already there into the union.
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);
143 }
144}
145
146// This is called in the Options constructor, though we could call it lazily if
147// that ends up being a performance problem.
148
150 // Check to see if we already did this.
151 if (m_required_options.size() != 0)
152 return;
153
154 // Check to see if there are any options.
155 int num_options = NumCommandOptions();
156 if (num_options == 0)
157 return;
158
159 auto opt_defs = GetDefinitions();
160 m_required_options.resize(1);
161 m_optional_options.resize(1);
162
163 // First count the number of option sets we've got. Ignore
164 // LLDB_ALL_OPTION_SETS...
165
166 uint32_t num_option_sets = 0;
167
168 for (const auto &def : opt_defs) {
169 uint32_t this_usage_mask = def.usage_mask;
170 if (this_usage_mask == LLDB_OPT_SET_ALL) {
171 if (num_option_sets == 0)
172 num_option_sets = 1;
173 } else {
174 for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++) {
175 if (this_usage_mask & (1 << j)) {
176 if (num_option_sets <= j)
177 num_option_sets = j + 1;
178 }
179 }
180 }
181 }
182
183 if (num_option_sets > 0) {
184 m_required_options.resize(num_option_sets);
185 m_optional_options.resize(num_option_sets);
186
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) {
190 if (def.required)
191 m_required_options[j].insert(def.short_option);
192 else
193 m_optional_options[j].insert(def.short_option);
194 }
195 }
196 }
197 }
198}
199
200uint32_t Options::NumCommandOptions() { return GetDefinitions().size(); }
201
203 // Check to see if this has already been done.
204 if (m_getopt_table.empty()) {
205 auto defs = GetDefinitions();
206 if (defs.empty())
207 return nullptr;
208
209 std::map<int, uint32_t> option_seen;
210
211 m_getopt_table.resize(defs.size() + 1);
212 for (size_t i = 0; i < defs.size(); ++i) {
213 const int short_opt = defs[i].short_option;
214
215 m_getopt_table[i].definition = &defs[i];
216 m_getopt_table[i].flag = nullptr;
217 m_getopt_table[i].val = short_opt;
218
219 auto [pos, inserted] = option_seen.try_emplace(short_opt, i);
220 if (!inserted && short_opt) {
221 m_getopt_table[i].val = 0;
222 StreamString strm;
223 if (defs[i].HasShortOption())
225 llvm::formatv(
226 "option[{0}] --{1} has a short option -{2} that "
227 "conflicts with option[{3}] --{4}, short option won't "
228 "be used for --{5}",
229 i, defs[i].long_option, short_opt, pos->second,
230 m_getopt_table[pos->second].definition->long_option,
231 defs[i].long_option)
232 .str());
233 else
235 llvm::formatv(
236 "option[{0}] --{1} has a short option {2:x} that "
237 "conflicts with option[{3}] --{4}, short option won't "
238 "be used for --{5}",
239 (int)i, defs[i].long_option, short_opt, pos->second,
240 m_getopt_table[pos->second].definition->long_option,
241 defs[i].long_option)
242 .str());
243 }
244 }
245
246 // getopt_long_only requires a NULL final entry in the table:
247
248 m_getopt_table.back().definition = nullptr;
249 m_getopt_table.back().flag = nullptr;
250 m_getopt_table.back().val = 0;
251 }
252
253 if (m_getopt_table.empty())
254 return nullptr;
255
256 return &m_getopt_table.front();
257}
258
259// This function takes INDENT, which tells how many spaces to output at the
260// front of each line; SPACES, which is a string containing 80 spaces; and
261// TEXT, which is the text that is to be output. It outputs the text, on
262// multiple lines if necessary, to RESULT, with INDENT spaces at the front of
263// each line. It breaks lines on spaces, tabs or newlines, shortening the line
264// if necessary to not break in the middle of a word. It assumes that each
265// output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
266
268 const OptionDefinition &option_def,
269 uint32_t output_max_columns,
270 bool use_color) {
271 std::string actual_text;
272 if (option_def.validator) {
273 if (const char *condition = option_def.validator->ShortConditionString()) {
274 actual_text = "[";
275 actual_text.append(condition);
276 actual_text.append("] ");
277 }
278 }
279 actual_text.append(
280 ansi::FormatAnsiTerminalCodes(option_def.usage_text, use_color));
281
282 ansi::OutputWordWrappedLines(strm, actual_text, output_max_columns,
283 use_color);
284}
285
286bool Options::SupportsLongOption(const char *long_option) {
287 if (!long_option || !long_option[0])
288 return false;
289
290 auto opt_defs = GetDefinitions();
291 if (opt_defs.empty())
292 return false;
293
294 const char *long_option_name = long_option;
295 if (long_option[0] == '-' && long_option[1] == '-')
296 long_option_name += 2;
297
298 for (auto &def : opt_defs) {
299 if (!def.long_option)
300 continue;
301
302 if (strcmp(def.long_option, long_option_name) == 0)
303 return true;
304 }
305
306 return false;
307}
308
314
315static bool PrintOption(const OptionDefinition &opt_def,
316 OptionDisplayType display_type, const char *header,
317 const char *footer, bool show_optional, Stream &strm) {
318 if (display_type == eDisplayShortOption && !opt_def.HasShortOption())
319 return false;
320
321 if (header && header[0])
322 strm.PutCString(header);
323
324 if (show_optional && !opt_def.required)
325 strm.PutChar('[');
326 const bool show_short_option =
327 opt_def.HasShortOption() && display_type != eDisplayLongOption;
328 if (show_short_option)
329 strm.Printf("-%c", opt_def.short_option);
330 else
331 strm.Printf("--%s", opt_def.long_option);
332 switch (opt_def.option_has_arg) {
334 break;
337 break;
338
340 strm.Printf("%s[<%s>]", show_short_option ? "" : "=",
342 break;
343 }
344 if (show_optional && !opt_def.required)
345 strm.PutChar(']');
346 if (footer && footer[0])
347 strm.PutCString(footer);
348 return true;
349}
350
352 uint32_t screen_width, bool use_color) {
353 auto opt_defs = GetDefinitions();
354 const uint32_t save_indent_level = strm.GetIndentLevel();
355 llvm::StringRef name = cmd.GetCommandName();
356 StreamString arguments_str;
357 cmd.GetFormattedCommandArguments(arguments_str);
358
359 const uint32_t num_options = NumCommandOptions();
360 if (num_options == 0)
361 return;
362
363 const bool only_print_args = cmd.IsDashDashCommand();
364 if (!only_print_args)
365 strm.PutCString("\nCommand Options Usage:\n");
366
367 strm.IndentMore(2);
368
369 // First, show each usage level set of options, e.g. <cmd> [options-for-
370 // level-0]
371 // <cmd>
372 // [options-for-level-1]
373 // etc.
374
375 if (!only_print_args) {
376 uint32_t num_option_sets = GetRequiredOptions().size();
377 for (uint32_t opt_set = 0; opt_set < num_option_sets; ++opt_set) {
378 if (opt_set > 0)
379 strm.Printf("\n");
380 strm.Indent(name);
381
382 // Different option sets may require different args.
383 StreamString args_str;
384 uint32_t opt_set_mask = 1 << opt_set;
385 cmd.GetFormattedCommandArguments(args_str, opt_set_mask);
386
387 // First go through and print all options that take no arguments as a
388 // single string. If a command has "-a" "-b" and "-c", this will show up
389 // as [-abc]
390
391 // We use a set here so that they will be sorted.
392 std::set<int> required_options;
393 std::set<int> optional_options;
394
395 for (auto &def : opt_defs) {
396 if (def.usage_mask & opt_set_mask && def.HasShortOption() &&
397 def.option_has_arg == OptionParser::eNoArgument) {
398 if (def.required) {
399 required_options.insert(def.short_option);
400 } else {
401 optional_options.insert(def.short_option);
402 }
403 }
404 }
405
406 if (!required_options.empty()) {
407 strm.PutCString(" -");
408 for (int short_option : required_options)
409 strm.PutChar(short_option);
410 }
411
412 if (!optional_options.empty()) {
413 strm.PutCString(" [-");
414 for (int short_option : optional_options)
415 strm.PutChar(short_option);
416 strm.PutChar(']');
417 }
418
419 // First go through and print the required options (list them up front).
420 for (auto &def : opt_defs) {
421 if (def.usage_mask & opt_set_mask && def.HasShortOption() &&
422 def.required && def.option_has_arg != OptionParser::eNoArgument)
423 PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm);
424 }
425
426 // Now go through again, and this time only print the optional options.
427 for (auto &def : opt_defs) {
428 if (def.usage_mask & opt_set_mask && !def.required &&
429 def.option_has_arg != OptionParser::eNoArgument)
430 PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm);
431 }
432
433 if (args_str.GetSize() > 0) {
434 if (cmd.WantsRawCommandString())
435 strm.Printf(" --");
436 strm << " " << args_str.GetString();
437 }
438 }
439 }
440
441 if ((only_print_args || cmd.WantsRawCommandString()) &&
442 arguments_str.GetSize() > 0) {
443 if (!only_print_args)
444 strm.PutChar('\n');
445 strm.Indent(name);
446 strm << " " << arguments_str.GetString();
447 }
448
449 if (!only_print_args) {
450 strm.Printf("\n\n");
451
452 // Now print out all the detailed information about the various options:
453 // long form, short form and help text:
454 // -short <argument> ( --long_name <argument> )
455 // help text
456
457 strm.IndentMore(5);
458
459 // Put the command options in a sorted container, so we can output
460 // them alphabetically by short_option.
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()));
465
466 // Go through each option, find the table entry and write out the detailed
467 // help information for that option.
468
469 bool first_option_printed = false;
470
471 for (auto pos : options_ordered) {
472 // Put a newline separation between arguments
473 if (first_option_printed)
474 strm.EOL();
475 else
476 first_option_printed = true;
477
478 OptionDefinition opt_def = opt_defs[pos.second];
479
480 strm.Indent();
481 if (opt_def.short_option && opt_def.HasShortOption()) {
482 PrintOption(opt_def, eDisplayShortOption, nullptr, nullptr, false,
483 strm);
484 PrintOption(opt_def, eDisplayLongOption, " ( ", " )", false, strm);
485 } else {
486 // Short option is not printable, just print long option
487 PrintOption(opt_def, eDisplayLongOption, nullptr, nullptr, false, strm);
488 }
489 strm.EOL();
490
491 strm.IndentMore(5);
492
493 if (opt_def.usage_text)
494 OutputFormattedUsageText(strm, opt_def, screen_width, use_color);
495 if (!opt_def.enum_values.empty()) {
496 strm.Indent();
497 strm.Printf("Values: ");
498 bool is_first = true;
499 for (const auto &enum_value : opt_def.enum_values) {
500 if (is_first) {
501 strm.Printf("%s", enum_value.string_value);
502 is_first = false;
503 }
504 else
505 strm.Printf(" | %s", enum_value.string_value);
506 }
507 strm.EOL();
508 }
509 strm.IndentLess(5);
510 }
511 }
512
513 // Restore the indent level
514 strm.SetIndentLevel(save_indent_level);
515}
516
518 bool options_are_valid = false;
519
520 int num_levels = GetRequiredOptions().size();
521 if (num_levels) {
522 for (int i = 0; i < num_levels && !options_are_valid; ++i) {
523 // This is the correct set of options if: 1). m_seen_options contains
524 // all of m_required_options[i] (i.e. all the required options at this
525 // level are a subset of m_seen_options); AND 2). { m_seen_options -
526 // m_required_options[i] is a subset of m_options_options[i] (i.e. all
527 // the rest of m_seen_options are in the set of optional options at this
528 // level.
529
530 // Check to see if all of m_required_options[i] are a subset of
531 // m_seen_options
533 // Construct the set difference: remaining_options = {m_seen_options} -
534 // {m_required_options[i]}
535 OptionSet remaining_options;
537 remaining_options);
538 // Check to see if remaining_options is a subset of
539 // m_optional_options[i]
540 if (IsASubset(remaining_options, GetOptionalOptions()[i]))
541 options_are_valid = true;
542 }
543 }
544 } else {
545 options_are_valid = true;
546 }
547
548 if (!options_are_valid)
549 return llvm::createStringError(
550 "invalid combination of options for the given command");
551
552 return llvm::Error::success();
553}
554
555// This function is called when we have been given a potentially incomplete set
556// of options, such as when an alias has been defined (more options might be
557// added at at the time the alias is invoked). We need to verify that the
558// options in the set m_seen_options are all part of a set that may be used
559// together, but m_seen_options may be missing some of the "required" options.
561 bool options_are_valid = false;
562
563 int num_levels = GetRequiredOptions().size();
564 if (num_levels) {
565 for (int i = 0; i < num_levels && !options_are_valid; ++i) {
566 // In this case we are treating all options as optional rather than
567 // required. Therefore a set of options is correct if m_seen_options is a
568 // subset of the union of m_required_options and m_optional_options.
569 OptionSet union_set;
571 union_set);
572 if (IsASubset(m_seen_options, union_set))
573 options_are_valid = true;
574 }
575 }
576
577 if (!options_are_valid)
578 return llvm::createStringError(
579 "invalid combination of options for the given command");
580
581 return llvm::Error::success();
582}
583
585 OptionElementVector &opt_element_vector,
586 CommandInterpreter &interpreter) {
587 // For now we just scan the completions to see if the cursor position is in
588 // an option or its argument. Otherwise we'll call HandleArgumentCompletion.
589 // In the future we can use completion to validate options as well if we
590 // want.
591
592 auto opt_defs = GetDefinitions();
593
594 llvm::StringRef cur_opt_str = request.GetCursorArgumentPrefix();
595 const bool use_color = interpreter.GetDebugger().GetUseColor();
596
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;
601 if (opt_pos == request.GetCursorIndex()) {
602 // We're completing the option itself.
603
604 if (opt_defs_index == OptionArgElement::eBareDash) {
605 // We're completing a bare dash. That means all options are open.
606 // FIXME: We should scan the other options provided and only complete
607 // options
608 // within the option group they belong to.
609 std::string opt_str = "-a";
610
611 for (auto &def : opt_defs) {
612 if (!def.short_option)
613 continue;
614 opt_str[1] = def.short_option;
616 def.usage_text, use_color));
617 }
618
619 return true;
620 } else if (opt_defs_index == OptionArgElement::eBareDoubleDash) {
621 std::string full_name("--");
622 for (auto &def : opt_defs) {
623 if (!def.short_option)
624 continue;
625
626 full_name.erase(full_name.begin() + 2, full_name.end());
627 full_name.append(def.long_option);
629 def.usage_text, use_color));
630 }
631 return true;
632 } else if (opt_defs_index != OptionArgElement::eUnrecognizedArg) {
633 // We recognized it, if it an incomplete long option, complete it
634 // anyway (getopt_long_only is happy with shortest unique string, but
635 // it's still a nice thing to do.) Otherwise return The string so the
636 // upper level code will know this is a full match and add the " ".
637 const OptionDefinition &opt = opt_defs[opt_defs_index];
638 llvm::StringRef long_option = opt.long_option;
639 if (cur_opt_str.starts_with("--") && cur_opt_str != long_option) {
640 request.AddCompletion(
641 "--" + long_option.str(),
643 return true;
644 } else
645 request.AddCompletion(request.GetCursorArgumentPrefix());
646 return true;
647 } else {
648 // FIXME - not handling wrong options yet:
649 // Check to see if they are writing a long option & complete it.
650 // I think we will only get in here if the long option table has two
651 // elements
652 // that are not unique up to this point. getopt_long_only does
653 // shortest unique match for long options already.
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))
658 request.AddCompletion(
659 "--" + long_option.str(),
660 ansi::FormatAnsiTerminalCodes(def.usage_text, use_color));
661 }
662 }
663 return true;
664 }
665
666 } else if (opt_arg_pos == request.GetCursorIndex()) {
667 // Okay the cursor is on the completion of an argument. See if it has a
668 // completion, otherwise return no matches. Note, opt_defs_index == -1
669 // means we're after an option, but that option doesn't exist. We'll
670 // end up treating that as an argument. Not sure we can do much better.
671 if (opt_defs_index != -1) {
672 HandleOptionArgumentCompletion(request, opt_element_vector, i,
673 interpreter);
674 return true;
675 } else {
676 // No completion callback means no completions...
677 return true;
678 }
679
680 } else {
681 // Not the last element, keep going.
682 continue;
683 }
684 }
685 return false;
686}
687
689 CompletionRequest &request, OptionElementVector &opt_element_vector,
690 int opt_element_index, CommandInterpreter &interpreter) {
691 auto opt_defs = GetDefinitions();
692 std::unique_ptr<SearchFilter> filter_up;
693
694 int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
695
696 // See if this is an enumeration type option, and if so complete it here:
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)
700 request.TryCompleteCurrentArg(enum_value.string_value);
701
702 // If this is a source file or symbol type completion, and there is a -shlib
703 // option somewhere in the supplied arguments, then make a search filter for
704 // that shared library.
705 // FIXME: Do we want to also have an "OptionType" so we don't have to match
706 // string names?
707
708 uint32_t completion_mask = opt_defs[opt_defs_index].completion_type;
709
710 if (completion_mask == 0) {
711 lldb::CommandArgumentType option_arg_type =
712 opt_defs[opt_defs_index].argument_type;
713 if (option_arg_type != eArgTypeNone) {
714 const CommandObject::ArgumentTableEntry *arg_entry =
716 opt_defs[opt_defs_index].argument_type);
717 if (arg_entry)
718 completion_mask = arg_entry->completion_type;
719 }
720 }
721
722 if (completion_mask & lldb::eSourceFileCompletion ||
723 completion_mask & lldb::eSymbolCompletion) {
724 for (size_t i = 0; i < opt_element_vector.size(); i++) {
725 int cur_defs_index = opt_element_vector[i].opt_defs_index;
726
727 // trying to use <0 indices will definitely cause problems
728 if (cur_defs_index == OptionArgElement::eUnrecognizedArg ||
729 cur_defs_index == OptionArgElement::eBareDash ||
730 cur_defs_index == OptionArgElement::eBareDoubleDash)
731 continue;
732
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;
735
736 // If this is the "shlib" option and there was an argument provided,
737 // restrict it to that shared library.
738 if (cur_opt_name && strcmp(cur_opt_name, "shlib") == 0 &&
739 cur_arg_pos != -1) {
740 const char *module_name =
741 request.GetParsedLine().GetArgumentAtIndex(cur_arg_pos);
742 if (module_name) {
743 FileSpec module_spec(module_name);
744 lldb::TargetSP target_sp =
745 interpreter.GetDebugger().GetSelectedTarget();
746 // Search filters require a target...
747 if (target_sp)
748 filter_up =
749 std::make_unique<SearchFilterByModule>(target_sp, module_spec);
750 }
751 break;
752 }
753 }
754 }
755
757 interpreter, completion_mask, request, filter_up.get());
758}
759
761 auto group_option_defs = group->GetDefinitions();
762 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
763 m_option_infos.push_back(OptionInfo(group, i));
764 m_option_defs.push_back(group_option_defs[i]);
765 }
766}
767
769 for (uint32_t i = 0; i < m_option_defs.size(); i++) {
770 OptionDefinition opt_def = m_option_defs[i];
771 if (opt_def.short_option == short_opt)
772 return m_option_infos[i].option_group;
773 }
774 return nullptr;
775}
776
777void OptionGroupOptions::Append(OptionGroup *group, uint32_t src_mask,
778 uint32_t dst_mask) {
779 auto group_option_defs = group->GetDefinitions();
780 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
781 if (group_option_defs[i].usage_mask & src_mask) {
782 m_option_infos.push_back(OptionInfo(group, i));
783 m_option_defs.push_back(group_option_defs[i]);
784 m_option_defs.back().usage_mask = dst_mask;
785 }
786 }
787}
788
790 OptionGroup *group, llvm::ArrayRef<llvm::StringRef> exclude_long_options) {
791 auto group_option_defs = group->GetDefinitions();
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))
795 continue;
796
797 m_option_infos.push_back(OptionInfo(group, i));
798 m_option_defs.push_back(definition);
799 }
800}
801
805
807 llvm::StringRef option_value,
808 ExecutionContext *execution_context) {
809 // After calling OptionGroupOptions::Append(...), you must finalize the
810 // groups by calling OptionGroupOptions::Finlize()
811 assert(m_did_finalize);
813 if (option_idx < m_option_infos.size()) {
814 error = m_option_infos[option_idx].option_group->SetOptionValue(
815 m_option_infos[option_idx].option_index, option_value,
816 execution_context);
817
818 } else {
819 error =
820 Status::FromErrorString("invalid option index"); // Shouldn't happen...
821 }
822 return error;
823}
824
826 ExecutionContext *execution_context) {
827 std::set<OptionGroup *> group_set;
828 OptionInfos::iterator pos, end = m_option_infos.end();
829 for (pos = m_option_infos.begin(); pos != end; ++pos) {
830 OptionGroup *group = pos->option_group;
831 if (group_set.find(group) == group_set.end()) {
832 group->OptionParsingStarting(execution_context);
833 group_set.insert(group);
834 }
835 }
836}
837Status
839 std::set<OptionGroup *> group_set;
841 OptionInfos::iterator pos, end = m_option_infos.end();
842 for (pos = m_option_infos.begin(); pos != end; ++pos) {
843 OptionGroup *group = pos->option_group;
844 if (group_set.find(group) == group_set.end()) {
845 error = group->OptionParsingFinished(execution_context);
846 group_set.insert(group);
847 if (error.Fail())
848 return error;
849 }
850 }
851 return error;
852}
853
854// OptionParser permutes the arguments while processing them, so we create a
855// temporary array holding to avoid modification of the input arguments. The
856// options themselves are never modified, but the API expects a char * anyway,
857// hence the const_cast.
858static std::vector<char *> GetArgvForParsing(const Args &args) {
859 std::vector<char *> result;
860 // OptionParser always skips the first argument as it is based on getopt().
861 result.push_back(const_cast<char *>("<FAKE-ARG0>"));
862 for (const Args::ArgEntry &entry : args)
863 result.push_back(const_cast<char *>(entry.c_str()));
864 result.push_back(nullptr);
865 return result;
866}
867
868// Given a permuted argument, find it's position in the original Args vector.
870 const Args &original) {
871 return llvm::find_if(
872 original, [arg](const Args::ArgEntry &D) { return D.c_str() == arg; });
873}
874
875// Given a permuted argument, find it's index in the original Args vector.
876static size_t FindOriginalIndex(const char *arg, const Args &original) {
877 return std::distance(original.begin(), FindOriginalIter(arg, original));
878}
879
880// Construct a new Args object, consisting of the entries from the original
881// arguments, but in the permuted order.
882static Args ReconstituteArgsAfterParsing(llvm::ArrayRef<char *> parsed,
883 const Args &original) {
884 Args result;
885 for (const char *arg : parsed) {
886 auto pos = FindOriginalIter(arg, original);
887 assert(pos != original.end());
888 result.AppendArgument(pos->ref(), pos->GetQuoteChar());
889 }
890 return result;
891}
892
893/// Find the index of the given option in the arguments. If the option takes an
894/// argument, the second index is the index of the value in args. Otherwise, the
895/// second index is LLDB_INVALID_INDEX64.
896static std::pair<size_t, size_t>
897FindArgumentIndexForOption(const Args &args, const Option &long_option) {
898 std::string short_opt = llvm::formatv("-{0}", char(long_option.val)).str();
899 std::string long_opt =
900 llvm::formatv("--{0}", long_option.definition->long_option).str();
901 for (const auto &entry : llvm::enumerate(args)) {
902 llvm::StringRef arg = entry.value().ref();
903 size_t idx = entry.index();
905 return {idx, LLDB_INVALID_INDEX64};
906 size_t val_idx;
907 if (arg == short_opt || arg.starts_with(long_opt))
908 val_idx = idx + 1;
909 else if (arg.starts_with(short_opt))
910 val_idx = idx;
911 return {idx, val_idx};
912 }
913
915}
916
917static std::string BuildShortOptions(const Option *long_options) {
918 std::string storage;
919 llvm::raw_string_ostream sstr(storage);
920
921 // Leading : tells getopt to return a : for a missing option argument AND to
922 // suppress error messages.
923 sstr << ":";
924
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) {
929 default:
931 break;
933 sstr << ":";
934 break;
936 sstr << "::";
937 break;
938 }
939 }
940 }
941 return storage;
942}
943
944llvm::Expected<Args> Options::ParseAlias(const Args &args,
945 OptionArgVector *option_arg_vector,
946 std::string &input_line) {
947 Option *long_options = GetLongOptions();
948
949 if (long_options == nullptr) {
950 return llvm::createStringError("invalid long options");
951 }
952
953 std::string short_options = BuildShortOptions(long_options);
954
955 Args args_copy = args;
956 std::vector<char *> argv = GetArgvForParsing(args);
957
958 std::unique_lock<std::mutex> lock;
960 int val;
961 while (true) {
962 int long_options_index = -1;
963 val = OptionParser::Parse(argv, short_options, long_options,
964 &long_options_index);
965
966 if (val == ':') {
967 return llvm::createStringError(llvm::inconvertibleErrorCode(),
968 "last option requires an argument");
969 }
970
971 if (val == -1)
972 break;
973
974 if (val == '?') {
975 return llvm::createStringError("unknown or ambiguous option");
976 }
977
978 if (val == 0)
979 continue;
980
981 OptionSeen(val);
982
983 // Look up the long option index
984 if (long_options_index == -1) {
985 for (int j = 0; long_options[j].definition || long_options[j].flag ||
986 long_options[j].val;
987 ++j) {
988 if (long_options[j].val == val) {
989 long_options_index = j;
990 break;
991 }
992 }
993 }
994
995 // See if the option takes an argument, and see if one was supplied.
996 if (long_options_index == -1) {
997 return llvm::createStringErrorV("invalid option with value '{0}'",
998 char(val));
999 }
1000
1001 StreamString option_str;
1002 option_str.Printf("-%c", val);
1003 const Option &opt = long_options[long_options_index];
1004 int has_arg = opt.definition ? opt.definition->option_has_arg
1006 const char *option_arg = nullptr;
1007 switch (has_arg) {
1009 if (OptionParser::GetOptionArgument() == nullptr) {
1010 return llvm::createStringError(
1011 llvm::formatv("Option '{0}' is missing argument specifier.",
1012 option_str.GetString())
1013 .str());
1014 }
1015 [[fallthrough]];
1017 option_arg = OptionParser::GetOptionArgument();
1018 [[fallthrough]];
1020 break;
1021 default:
1022 return llvm::createStringError(
1023 llvm::formatv("error with options table; invalid value in has_arg "
1024 "field for option '{0}'.",
1025 char(val))
1026 .str());
1027 }
1028 // Find option in the argument list; also see if it was supposed to take an
1029 // argument and if one was supplied. Remove option (and argument, if
1030 // given) from the argument list. Also remove them from the
1031 // raw_input_string, if one was passed in.
1032 // Note: We also need to preserve any option argument values that were
1033 // surrounded by backticks, as we lose track of them in the
1034 // option_args_vector.
1035 auto [idx, val_idx] = FindArgumentIndexForOption(args_copy, opt);
1036 std::string option_to_insert;
1037 if (option_arg) {
1038 if (val_idx != LLDB_INVALID_INDEX64 && val_idx < args_copy.size()) {
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 += "`";
1045 } else
1046 option_to_insert = option_arg;
1047 } else
1048 option_to_insert = CommandInterpreter::g_no_argument;
1049
1050 option_arg_vector->emplace_back(std::string(option_str.GetString()),
1051 has_arg, option_to_insert);
1052
1053 if (idx == LLDB_INVALID_INDEX64)
1054 continue;
1055
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());
1061 }
1062 args_copy.DeleteArgumentAtIndex(idx);
1063 if ((option_to_insert != CommandInterpreter::g_no_argument) &&
1064 (OptionParser::GetOptionArgument() != nullptr) &&
1065 (idx < args_copy.GetArgumentCount()) &&
1066 (args_copy[idx].ref() == OptionParser::GetOptionArgument())) {
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());
1071 }
1072 args_copy.DeleteArgumentAtIndex(idx);
1073 }
1074 }
1075
1076 return std::move(args_copy);
1077}
1078
1080 uint32_t cursor_index) {
1081 OptionElementVector option_element_vector;
1082 Option *long_options = GetLongOptions();
1083 option_element_vector.clear();
1084
1085 if (long_options == nullptr)
1086 return option_element_vector;
1087
1088 std::string short_options = BuildShortOptions(long_options);
1089
1090 std::unique_lock<std::mutex> lock;
1093
1094 int val;
1095 auto opt_defs = GetDefinitions();
1096
1097 std::vector<char *> dummy_vec = GetArgvForParsing(args);
1098
1099 bool failed_once = false;
1100 uint32_t dash_dash_pos = -1;
1101
1102 while (true) {
1103 bool missing_argument = false;
1104 int long_options_index = -1;
1105
1106 val = OptionParser::Parse(dummy_vec, short_options, long_options,
1107 &long_options_index);
1108
1109 if (val == -1) {
1110 // When we're completing a "--" which is the last option on line,
1111 if (failed_once)
1112 break;
1113
1114 failed_once = true;
1115
1116 // If this is a bare "--" we mark it as such so we can complete it
1117 // successfully later. Handling the "--" is a little tricky, since that
1118 // may mean end of options or arguments, or the user might want to
1119 // complete options by long name. I make this work by checking whether
1120 // the cursor is in the "--" argument, and if so I assume we're
1121 // completing the long option, otherwise I let it pass to
1122 // OptionParser::Parse which will terminate the option parsing. Note, in
1123 // either case we continue parsing the line so we can figure out what
1124 // other options were passed. This will be useful when we come to
1125 // restricting completions based on what other options we've seen on the
1126 // line.
1127
1128 if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1129 dummy_vec.size() &&
1130 (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) {
1131 dash_dash_pos = FindOriginalIndex(
1132 dummy_vec[OptionParser::GetOptionIndex() - 1], args);
1133 if (dash_dash_pos == cursor_index) {
1134 option_element_vector.push_back(
1137 continue;
1138 } else
1139 break;
1140 } else
1141 break;
1142 } else if (val == '?') {
1143 option_element_vector.push_back(OptionArgElement(
1146 args),
1148 continue;
1149 } else if (val == 0) {
1150 continue;
1151 } else if (val == ':') {
1152 // This is a missing argument.
1154 missing_argument = true;
1155 }
1156
1157 OptionSeen(val);
1158
1159 // Look up the long option index
1160 if (long_options_index == -1) {
1161 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1162 long_options[j].val;
1163 ++j) {
1164 if (long_options[j].val == val) {
1165 long_options_index = j;
1166 break;
1167 }
1168 }
1169 }
1170
1171 // See if the option takes an argument, and see if one was supplied.
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)
1176 continue;
1177 opt_defs_index = i;
1178 break;
1179 }
1180
1181 const OptionDefinition *def = long_options[long_options_index].definition;
1182 int has_arg =
1183 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1184 switch (has_arg) {
1186 option_element_vector.push_back(OptionArgElement(
1187 opt_defs_index,
1189 args),
1190 0));
1191 break;
1193 if (OptionParser::GetOptionArgument() != nullptr) {
1194 int arg_index;
1195 if (missing_argument)
1196 arg_index = -1;
1197 else
1198 arg_index = OptionParser::GetOptionIndex() - 2;
1199
1200 option_element_vector.push_back(OptionArgElement(
1201 opt_defs_index,
1203 args),
1204 arg_index));
1205 } else {
1206 option_element_vector.push_back(OptionArgElement(
1207 opt_defs_index,
1209 args),
1210 -1));
1211 }
1212 break;
1214 option_element_vector.push_back(OptionArgElement(
1215 opt_defs_index,
1217 args),
1219 args)));
1220 break;
1221 default:
1222 // The options table is messed up. Here we'll just continue
1223 option_element_vector.push_back(OptionArgElement(
1226 args),
1228 break;
1229 }
1230 } else {
1231 option_element_vector.push_back(OptionArgElement(
1234 args),
1236 }
1237 }
1238
1239 // Finally we have to handle the case where the cursor index points at a
1240 // single "-". We want to mark that in the option_element_vector, but only
1241 // if it is not after the "--". But it turns out that OptionParser::Parse
1242 // just ignores an isolated "-". So we have to look it up by hand here. We
1243 // only care if it is AT the cursor position. Note, a single quoted dash is
1244 // not the same as a single dash...
1245
1246 const Args::ArgEntry &cursor = args[cursor_index];
1247 if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1248 cursor_index < dash_dash_pos) &&
1249 !cursor.IsQuoted() && cursor.ref() == "-") {
1250 option_element_vector.push_back(
1253 }
1254 return option_element_vector;
1255}
1256
1257llvm::Expected<Args> Options::Parse(const Args &args,
1258 ExecutionContext *execution_context,
1259 lldb::PlatformSP platform_sp,
1260 bool require_validation) {
1261 Status error;
1262 Option *long_options = GetLongOptions();
1263 if (long_options == nullptr) {
1264 return llvm::createStringError("invalid long options");
1265 }
1266
1267 std::string short_options = BuildShortOptions(long_options);
1268 std::vector<char *> argv = GetArgvForParsing(args);
1269
1270 std::unique_lock<std::mutex> lock;
1272 while (true) {
1273 int long_options_index = -1;
1274 int val = OptionParser::Parse(argv, short_options, long_options,
1275 &long_options_index);
1276
1277 if (val == ':') {
1278 error = Status::FromErrorString("last option requires an argument");
1279 break;
1280 }
1281
1282 if (val == -1)
1283 break;
1284
1285 // Did we get an error?
1286 if (val == '?') {
1287 // Account for "argv[0]" and that it points to the next option.
1288 int idx = OptionParser::GetOptionIndex() - 2;
1289 if (idx >= 0 && (size_t)idx < args.GetArgumentCount())
1290 error = Status::FromError(llvm::make_error<OptionParseError>(
1291 args[idx], "unknown or ambiguous option"));
1292 else
1293 error = Status("unknown or ambiguous option");
1294
1295 break;
1296 }
1297 // The option auto-set itself
1298 if (val == 0)
1299 continue;
1300
1301 OptionSeen(val);
1302
1303 // Lookup the long option index
1304 if (long_options_index == -1) {
1305 for (int i = 0; long_options[i].definition || long_options[i].flag ||
1306 long_options[i].val;
1307 ++i) {
1308 if (long_options[i].val == val) {
1309 long_options_index = i;
1310 break;
1311 }
1312 }
1313 }
1314 // Call the callback with the option
1315 if (long_options_index >= 0 &&
1316 long_options[long_options_index].definition) {
1317 const OptionDefinition *def = long_options[long_options_index].definition;
1318
1319 if (!platform_sp) {
1320 // User did not pass in an explicit platform. Try to grab from the
1321 // execution context.
1322 TargetSP target_sp =
1323 execution_context ? execution_context->GetTargetSP() : TargetSP();
1324 platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
1325 }
1327
1328 if (!platform_sp && require_validation) {
1329 // Caller requires validation but we cannot validate as we don't have
1330 // the mandatory platform against which to validate.
1331 return llvm::createStringError(
1332 "cannot validate options: no platform available");
1333 }
1334
1335 bool validation_failed = false;
1336 if (platform_sp) {
1337 // Ensure we have an execution context, empty or not.
1338 ExecutionContext dummy_context;
1339 ExecutionContext *exe_ctx_p =
1340 execution_context ? execution_context : &dummy_context;
1341 if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
1342 validation_failed = true;
1344 "Option \"%s\" invalid. %s", def->long_option,
1346 }
1347 }
1348
1349 // As long as validation didn't fail, we set the option value.
1350 if (!validation_failed)
1351 error =
1352 SetOptionValue(long_options_index,
1354 ? nullptr
1356 execution_context);
1357 // If the Option setting returned an error, we should stop parsing
1358 // and return the error.
1359 if (error.Fail())
1360 break;
1361 } else {
1363 "invalid option with value '%i'", val);
1364 }
1365 }
1366
1367 if (error.Fail())
1368 return error.ToError();
1369
1370 argv.pop_back();
1371 argv.erase(argv.begin(), argv.begin() + OptionParser::GetOptionIndex());
1372 return ReconstituteArgsAfterParsing(argv, args);
1373}
1374
1376 llvm::StringRef option_arg, const char short_option,
1377 llvm::StringRef long_option, llvm::StringRef additional_context) {
1378 std::string buffer;
1379 llvm::raw_string_ostream stream(buffer);
1380 stream << "invalid value ('" << option_arg << "')";
1381 if (short_option)
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);
1388}
static llvm::raw_ostream & error(Stream &strm)
static Args ReconstituteArgsAfterParsing(llvm::ArrayRef< char * > parsed, const Args &original)
Definition Options.cpp:882
static std::string BuildShortOptions(const Option *long_options)
Definition Options.cpp:917
static std::vector< char * > GetArgvForParsing(const Args &args)
Definition Options.cpp:858
static bool PrintOption(const OptionDefinition &opt_def, OptionDisplayType display_type, const char *header, const char *footer, bool show_optional, Stream &strm)
Definition Options.cpp:315
static Args::const_iterator FindOriginalIter(const char *arg, const Args &original)
Definition Options.cpp:869
OptionDisplayType
Definition Options.cpp:309
@ eDisplayShortOption
Definition Options.cpp:311
@ eDisplayBestOption
Definition Options.cpp:310
@ eDisplayLongOption
Definition Options.cpp:312
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.
Definition Options.cpp:897
static size_t FindOriginalIndex(const char *arg, const Args &original)
Definition Options.cpp:876
A command line argument class.
Definition Args.h:33
std::vector< ArgEntry >::const_iterator const_iterator
Definition Args.h:134
void DeleteArgumentAtIndex(size_t idx)
Deletes the argument value at index if idx is a valid argument index.
Definition Args.cpp:359
const_iterator begin() const
Definition Args.h:136
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition Args.cpp:332
size_t size() const
Definition Args.h:139
const_iterator end() const
Definition Args.h:137
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
static bool InvokeCommonCompletionCallbacks(CommandInterpreter &interpreter, uint32_t completion_mask, lldb_private::CompletionRequest &request, SearchFilter *searcher)
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)
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.
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.
lldb::TargetSP GetSelectedTarget()
Definition Debugger.h:199
bool GetUseColor() const
Definition Debugger.cpp:525
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.
A file utility class.
Definition FileSpec.h:57
void OptionParsingStarting(ExecutionContext *execution_context) override
Definition Options.cpp:825
std::vector< OptionDefinition > m_option_defs
Definition Options.h:334
const OptionGroup * GetGroupWithOption(char short_opt)
Definition Options.cpp:768
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
Definition Options.cpp:806
Status OptionParsingFinished(ExecutionContext *execution_context) override
Definition Options.cpp:838
void Append(OptionGroup *group)
Append options from a OptionGroup class.
Definition Options.cpp:760
virtual Status OptionParsingFinished(ExecutionContext *execution_context)
Definition Options.h:248
virtual llvm::ArrayRef< OptionDefinition > GetDefinitions()=0
virtual void OptionParsingStarting(ExecutionContext *execution_context)=0
OptionParseError(DiagnosticDetail detail)
Definition Options.cpp:43
std::vector< DiagnosticDetail > m_details
Definition Options.cpp:39
llvm::ArrayRef< DiagnosticDetail > GetDetails() const override
Definition Options.cpp:58
OptionParseError(const Args::ArgEntry &arg, std::string msg)
Definition Options.cpp:46
std::unique_ptr< CloneableError > Clone() const override
Definition Options.cpp:55
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 char * GetOptionArgument()
static void EnableError(bool error)
void OptionsSetUnion(const OptionSet &set_a, const OptionSet &set_b, OptionSet &union_set)
Definition Options.cpp:128
void GenerateOptionUsage(Stream &strm, CommandObject &cmd, uint32_t screen_width, bool use_color)
Definition Options.cpp:351
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.
Definition Options.cpp:688
llvm::Error VerifyOptions()
Definition Options.cpp:517
virtual Status OptionParsingFinished(ExecutionContext *execution_context)
Definition Options.h:226
llvm::Error VerifyPartialOptions()
Definition Options.cpp:560
virtual Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context)=0
Set the value of an option.
uint32_t NumCommandOptions()
Definition Options.cpp:200
virtual void OptionParsingStarting(ExecutionContext *execution_context)=0
void OptionSeen(int short_option)
Definition Options.cpp:84
virtual llvm::ArrayRef< OptionDefinition > GetDefinitions()
Definition Options.h:98
Status NotifyOptionParsingFinished(ExecutionContext *execution_context)
Definition Options.cpp:80
Option * GetLongOptions()
Get the option definitions to use when parsing Args options.
Definition Options.cpp:202
OptionSetVector m_optional_options
Definition Options.h:201
void NotifyOptionParsingStarting(ExecutionContext *execution_context)
Definition Options.cpp:73
llvm::Expected< Args > ParseAlias(const Args &args, OptionArgVector *option_arg_vector, std::string &input_line)
Definition Options.cpp:944
std::set< int > OptionSet
Definition Options.h:195
void OutputFormattedUsageText(Stream &strm, const OptionDefinition &option_def, uint32_t output_max_columns, bool use_color)
Definition Options.cpp:267
OptionSetVector m_required_options
Definition Options.h:200
OptionSetVector & GetOptionalOptions()
Definition Options.h:208
size_t OptionsSetDiff(const OptionSet &set_a, const OptionSet &set_b, OptionSet &diffs)
Definition Options.cpp:108
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.
Definition Options.cpp:584
bool IsASubset(const OptionSet &set_a, const OptionSet &set_b)
Definition Options.cpp:88
bool SupportsLongOption(const char *long_option)
Definition Options.cpp:286
std::vector< Option > m_getopt_table
Definition Options.h:198
llvm::Expected< Args > Parse(const Args &args, ExecutionContext *execution_context, lldb::PlatformSP platform_sp, bool require_validation)
Parse the provided arguments.
Definition Options.cpp:1257
OptionSetVector & GetRequiredOptions()
Definition Options.h:203
OptionSet m_seen_options
Definition Options.h:199
OptionElementVector ParseForCompletion(const Args &args, uint32_t cursor_index)
Definition Options.cpp:1079
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:155
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:132
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:129
void SetIndentLevel(unsigned level)
Set the current indentation level.
Definition Stream.cpp:194
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:153
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:202
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:199
unsigned GetIndentLevel() const
Get the current indentation level.
Definition Stream.cpp:191
#define LLDB_MAX_NUM_OPTION_SETS
Option Set definitions.
#define LLDB_OPT_SET_ALL
#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
Definition Options.h:43
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.
Definition Options.cpp:1375
std::vector< std::tuple< std::string, int, std::string > > OptionArgVector
Definition Options.h:29
@ eSourceFileCompletion
std::shared_ptr< lldb_private::Platform > PlatformSP
std::shared_ptr< lldb_private::Target > TargetSP
const char * c_str() const
Definition Args.h:51
llvm::StringRef ref() const
Definition Args.h:50
bool IsQuoted() const
Returns true if this argument was quoted in any way.
Definition Args.h:54
std::optional< uint16_t > GetPos() const
Definition Args.h:56
Entries in the main argument information table.
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