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