1 //===-- Options.cpp ---------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Interpreter/Options.h"
17 #include "lldb/Host/OptionParser.h"
18 #include "lldb/Interpreter/CommandCompletions.h"
19 #include "lldb/Interpreter/CommandInterpreter.h"
20 #include "lldb/Interpreter/CommandObject.h"
21 #include "lldb/Interpreter/CommandReturnObject.h"
22 #include "lldb/Target/Target.h"
23 #include "lldb/Utility/StreamString.h"
26 using namespace lldb_private;
28 //-------------------------------------------------------------------------
30 //-------------------------------------------------------------------------
31 Options::Options() : m_getopt_table() { BuildValidOptionSets(); }
33 Options::~Options() {}
35 void Options::NotifyOptionParsingStarting(ExecutionContext *execution_context) {
36 m_seen_options.clear();
37 // Let the subclass reset its option values
38 OptionParsingStarting(execution_context);
42 Options::NotifyOptionParsingFinished(ExecutionContext *execution_context) {
43 return OptionParsingFinished(execution_context);
46 void Options::OptionSeen(int option_idx) { m_seen_options.insert(option_idx); }
48 // Returns true is set_a is a subset of set_b; Otherwise returns false.
50 bool Options::IsASubset(const OptionSet &set_a, const OptionSet &set_b) {
51 bool is_a_subset = true;
52 OptionSet::const_iterator pos_a;
53 OptionSet::const_iterator pos_b;
55 // set_a is a subset of set_b if every member of set_a is also a member of
58 for (pos_a = set_a.begin(); pos_a != set_a.end() && is_a_subset; ++pos_a) {
59 pos_b = set_b.find(*pos_a);
60 if (pos_b == set_b.end())
67 // Returns the set difference set_a - set_b, i.e. { x | ElementOf (x, set_a) &&
68 // !ElementOf (x, set_b) }
70 size_t Options::OptionsSetDiff(const OptionSet &set_a, const OptionSet &set_b,
73 OptionSet::const_iterator pos_a;
74 OptionSet::const_iterator pos_b;
76 for (pos_a = set_a.begin(); pos_a != set_a.end(); ++pos_a) {
77 pos_b = set_b.find(*pos_a);
78 if (pos_b == set_b.end()) {
87 // Returns the union of set_a and set_b. Does not put duplicate members into
90 void Options::OptionsSetUnion(const OptionSet &set_a, const OptionSet &set_b,
91 OptionSet &union_set) {
92 OptionSet::const_iterator pos;
93 OptionSet::iterator pos_union;
95 // Put all the elements of set_a into the union.
97 for (pos = set_a.begin(); pos != set_a.end(); ++pos)
98 union_set.insert(*pos);
100 // Put all the elements of set_b that are not already there into the union.
101 for (pos = set_b.begin(); pos != set_b.end(); ++pos) {
102 pos_union = union_set.find(*pos);
103 if (pos_union == union_set.end())
104 union_set.insert(*pos);
108 bool Options::VerifyOptions(CommandReturnObject &result) {
109 bool options_are_valid = false;
111 int num_levels = GetRequiredOptions().size();
113 for (int i = 0; i < num_levels && !options_are_valid; ++i) {
114 // This is the correct set of options if: 1). m_seen_options contains
115 // all of m_required_options[i] (i.e. all the required options at this
116 // level are a subset of m_seen_options); AND 2). { m_seen_options -
117 // m_required_options[i] is a subset of m_options_options[i] (i.e. all
118 // the rest of m_seen_options are in the set of optional options at this
121 // Check to see if all of m_required_options[i] are a subset of
123 if (IsASubset(GetRequiredOptions()[i], m_seen_options)) {
124 // Construct the set difference: remaining_options = {m_seen_options} -
125 // {m_required_options[i]}
126 OptionSet remaining_options;
127 OptionsSetDiff(m_seen_options, GetRequiredOptions()[i],
129 // Check to see if remaining_options is a subset of
130 // m_optional_options[i]
131 if (IsASubset(remaining_options, GetOptionalOptions()[i]))
132 options_are_valid = true;
136 options_are_valid = true;
139 if (options_are_valid) {
140 result.SetStatus(eReturnStatusSuccessFinishNoResult);
142 result.AppendError("invalid combination of options for the given command");
143 result.SetStatus(eReturnStatusFailed);
146 return options_are_valid;
149 // This is called in the Options constructor, though we could call it lazily if
150 // that ends up being a performance problem.
152 void Options::BuildValidOptionSets() {
153 // Check to see if we already did this.
154 if (m_required_options.size() != 0)
157 // Check to see if there are any options.
158 int num_options = NumCommandOptions();
159 if (num_options == 0)
162 auto opt_defs = GetDefinitions();
163 m_required_options.resize(1);
164 m_optional_options.resize(1);
166 // First count the number of option sets we've got. Ignore
167 // LLDB_ALL_OPTION_SETS...
169 uint32_t num_option_sets = 0;
171 for (const auto &def : opt_defs) {
172 uint32_t this_usage_mask = def.usage_mask;
173 if (this_usage_mask == LLDB_OPT_SET_ALL) {
174 if (num_option_sets == 0)
177 for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++) {
178 if (this_usage_mask & (1 << j)) {
179 if (num_option_sets <= j)
180 num_option_sets = j + 1;
186 if (num_option_sets > 0) {
187 m_required_options.resize(num_option_sets);
188 m_optional_options.resize(num_option_sets);
190 for (const auto &def : opt_defs) {
191 for (uint32_t j = 0; j < num_option_sets; j++) {
192 if (def.usage_mask & 1 << j) {
194 m_required_options[j].insert(def.short_option);
196 m_optional_options[j].insert(def.short_option);
203 uint32_t Options::NumCommandOptions() { return GetDefinitions().size(); }
205 Option *Options::GetLongOptions() {
206 // Check to see if this has already been done.
207 if (m_getopt_table.empty()) {
208 auto defs = GetDefinitions();
212 std::map<int, uint32_t> option_seen;
214 m_getopt_table.resize(defs.size() + 1);
215 for (size_t i = 0; i < defs.size(); ++i) {
216 const int short_opt = defs[i].short_option;
218 m_getopt_table[i].definition = &defs[i];
219 m_getopt_table[i].flag = nullptr;
220 m_getopt_table[i].val = short_opt;
222 if (option_seen.find(short_opt) == option_seen.end()) {
223 option_seen[short_opt] = i;
224 } else if (short_opt) {
225 m_getopt_table[i].val = 0;
226 std::map<int, uint32_t>::const_iterator pos =
227 option_seen.find(short_opt);
229 if (isprint8(short_opt))
230 Host::SystemLog(Host::eSystemLogError,
231 "option[%u] --%s has a short option -%c that "
232 "conflicts with option[%u] --%s, short option won't "
233 "be used for --%s\n",
234 (int)i, defs[i].long_option, short_opt, pos->second,
235 m_getopt_table[pos->second].definition->long_option,
236 defs[i].long_option);
238 Host::SystemLog(Host::eSystemLogError,
239 "option[%u] --%s has a short option 0x%x that "
240 "conflicts with option[%u] --%s, short option won't "
241 "be used for --%s\n",
242 (int)i, defs[i].long_option, short_opt, pos->second,
243 m_getopt_table[pos->second].definition->long_option,
244 defs[i].long_option);
248 // getopt_long_only requires a NULL final entry in the table:
250 m_getopt_table.back().definition = nullptr;
251 m_getopt_table.back().flag = nullptr;
252 m_getopt_table.back().val = 0;
255 if (m_getopt_table.empty())
258 return &m_getopt_table.front();
261 // This function takes INDENT, which tells how many spaces to output at the
262 // front of each line; SPACES, which is a string containing 80 spaces; and
263 // TEXT, which is the text that is to be output. It outputs the text, on
264 // multiple lines if necessary, to RESULT, with INDENT spaces at the front of
265 // each line. It breaks lines on spaces, tabs or newlines, shortening the line
266 // if necessary to not break in the middle of a word. It assumes that each
267 // output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
269 void Options::OutputFormattedUsageText(Stream &strm,
270 const OptionDefinition &option_def,
271 uint32_t output_max_columns) {
272 std::string actual_text;
273 if (option_def.validator) {
274 const char *condition = option_def.validator->ShortConditionString();
277 actual_text.append(condition);
278 actual_text.append("] ");
281 actual_text.append(option_def.usage_text);
283 // Will it all fit on one line?
285 if (static_cast<uint32_t>(actual_text.length() + strm.GetIndentLevel()) <
286 output_max_columns) {
287 // Output it as a single line.
288 strm.Indent(actual_text.c_str());
291 // We need to break it up into multiple lines.
293 int text_width = output_max_columns - strm.GetIndentLevel() - 1;
296 int final_end = actual_text.length();
299 while (end < final_end) {
300 // Don't start the 'text' on a space, since we're already outputting the
302 while ((start < final_end) && (actual_text[start] == ' '))
305 end = start + text_width;
309 // If we're not at the end of the text, make sure we break the line on
311 while (end > start && actual_text[end] != ' ' &&
312 actual_text[end] != '\t' && actual_text[end] != '\n')
316 sub_len = end - start;
320 assert(start < final_end);
321 assert(start + sub_len <= final_end);
322 strm.Write(actual_text.c_str() + start, sub_len);
329 bool Options::SupportsLongOption(const char *long_option) {
330 if (!long_option || !long_option[0])
333 auto opt_defs = GetDefinitions();
334 if (opt_defs.empty())
337 const char *long_option_name = long_option;
338 if (long_option[0] == '-' && long_option[1] == '-')
339 long_option_name += 2;
341 for (auto &def : opt_defs) {
342 if (!def.long_option)
345 if (strcmp(def.long_option, long_option_name) == 0)
352 enum OptionDisplayType {
358 static bool PrintOption(const OptionDefinition &opt_def,
359 OptionDisplayType display_type, const char *header,
360 const char *footer, bool show_optional, Stream &strm) {
361 const bool has_short_option = isprint8(opt_def.short_option) != 0;
363 if (display_type == eDisplayShortOption && !has_short_option)
366 if (header && header[0])
367 strm.PutCString(header);
369 if (show_optional && !opt_def.required)
371 const bool show_short_option =
372 has_short_option && display_type != eDisplayLongOption;
373 if (show_short_option)
374 strm.Printf("-%c", opt_def.short_option);
376 strm.Printf("--%s", opt_def.long_option);
377 switch (opt_def.option_has_arg) {
378 case OptionParser::eNoArgument:
380 case OptionParser::eRequiredArgument:
381 strm.Printf(" <%s>", CommandObject::GetArgumentName(opt_def.argument_type));
384 case OptionParser::eOptionalArgument:
385 strm.Printf("%s[<%s>]", show_short_option ? "" : "=",
386 CommandObject::GetArgumentName(opt_def.argument_type));
389 if (show_optional && !opt_def.required)
391 if (footer && footer[0])
392 strm.PutCString(footer);
396 void Options::GenerateOptionUsage(Stream &strm, CommandObject *cmd,
397 uint32_t screen_width) {
398 const bool only_print_args = cmd->IsDashDashCommand();
400 auto opt_defs = GetDefinitions();
401 const uint32_t save_indent_level = strm.GetIndentLevel();
402 llvm::StringRef name;
404 StreamString arguments_str;
407 name = cmd->GetCommandName();
408 cmd->GetFormattedCommandArguments(arguments_str);
412 strm.PutCString("\nCommand Options Usage:\n");
416 // First, show each usage level set of options, e.g. <cmd> [options-for-
419 // [options-for-level-1]
422 const uint32_t num_options = NumCommandOptions();
423 if (num_options == 0)
426 uint32_t num_option_sets = GetRequiredOptions().size();
430 if (!only_print_args) {
431 for (uint32_t opt_set = 0; opt_set < num_option_sets; ++opt_set) {
432 uint32_t opt_set_mask;
434 opt_set_mask = 1 << opt_set;
439 // Different option sets may require different args.
440 StreamString args_str;
442 cmd->GetFormattedCommandArguments(args_str, opt_set_mask);
444 // First go through and print all options that take no arguments as a
445 // single string. If a command has "-a" "-b" and "-c", this will show up
448 std::set<int> options;
449 std::set<int>::const_iterator options_pos, options_end;
450 for (auto &def : opt_defs) {
451 if (def.usage_mask & opt_set_mask && isprint8(def.short_option)) {
452 // Add current option to the end of out_stream.
454 if (def.required && def.option_has_arg == OptionParser::eNoArgument) {
455 options.insert(def.short_option);
460 if (!options.empty()) {
461 // We have some required options with no arguments
462 strm.PutCString(" -");
463 for (i = 0; i < 2; ++i)
464 for (options_pos = options.begin(), options_end = options.end();
465 options_pos != options_end; ++options_pos) {
466 if (i == 0 && ::islower(*options_pos))
468 if (i == 1 && ::isupper(*options_pos))
470 strm << (char)*options_pos;
475 for (auto &def : opt_defs) {
476 if (def.usage_mask & opt_set_mask && isprint8(def.short_option)) {
477 // Add current option to the end of out_stream.
480 def.option_has_arg == OptionParser::eNoArgument) {
481 options.insert(def.short_option);
486 if (!options.empty()) {
487 // We have some required options with no arguments
488 strm.PutCString(" [-");
489 for (i = 0; i < 2; ++i)
490 for (options_pos = options.begin(), options_end = options.end();
491 options_pos != options_end; ++options_pos) {
492 if (i == 0 && ::islower(*options_pos))
494 if (i == 1 && ::isupper(*options_pos))
496 strm << (char)*options_pos;
501 // First go through and print the required options (list them up front).
503 for (auto &def : opt_defs) {
504 if (def.usage_mask & opt_set_mask && isprint8(def.short_option)) {
505 if (def.required && def.option_has_arg != OptionParser::eNoArgument)
506 PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm);
510 // Now go through again, and this time only print the optional options.
512 for (auto &def : opt_defs) {
513 if (def.usage_mask & opt_set_mask) {
514 // Add current option to the end of out_stream.
516 if (!def.required && def.option_has_arg != OptionParser::eNoArgument)
517 PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm);
521 if (args_str.GetSize() > 0) {
522 if (cmd->WantsRawCommandString() && !only_print_args)
525 strm << " " << args_str.GetString();
532 if (cmd && (only_print_args || cmd->WantsRawCommandString()) &&
533 arguments_str.GetSize() > 0) {
534 if (!only_print_args)
537 strm << " " << arguments_str.GetString();
542 if (!only_print_args) {
543 // Now print out all the detailed information about the various options:
544 // long form, short form and help text:
545 // -short <argument> ( --long_name <argument> )
548 // This variable is used to keep track of which options' info we've printed
549 // out, because some options can be in more than one usage level, but we
550 // only want to print the long form of its information once.
552 std::multimap<int, uint32_t> options_seen;
555 // Put the unique command options in a vector & sort it, so we can output
556 // them alphabetically (by short_option) when writing out detailed help for
560 for (auto &def : opt_defs)
561 options_seen.insert(std::make_pair(def.short_option, i++));
563 // Go through the unique'd and alphabetically sorted vector of options,
564 // find the table entry for each option and write out the detailed help
565 // information for that option.
567 bool first_option_printed = false;
569 for (auto pos : options_seen) {
571 // Print out the help information for this option.
573 // Put a newline separation between arguments
574 if (first_option_printed)
577 first_option_printed = true;
579 CommandArgumentType arg_type = opt_defs[i].argument_type;
581 StreamString arg_name_str;
582 arg_name_str.Printf("<%s>", CommandObject::GetArgumentName(arg_type));
585 if (opt_defs[i].short_option && isprint8(opt_defs[i].short_option)) {
586 PrintOption(opt_defs[i], eDisplayShortOption, nullptr, nullptr, false,
588 PrintOption(opt_defs[i], eDisplayLongOption, " ( ", " )", false, strm);
590 // Short option is not printable, just print long option
591 PrintOption(opt_defs[i], eDisplayLongOption, nullptr, nullptr, false,
598 if (opt_defs[i].usage_text)
599 OutputFormattedUsageText(strm, opt_defs[i], screen_width);
600 if (!opt_defs[i].enum_values.empty()) {
602 strm.Printf("Values: ");
603 bool is_first = true;
604 for (const auto &enum_value : opt_defs[i].enum_values) {
606 strm.Printf("%s", enum_value.string_value);
610 strm.Printf(" | %s", enum_value.string_value);
618 // Restore the indent level
619 strm.SetIndentLevel(save_indent_level);
622 // This function is called when we have been given a potentially incomplete set
623 // of options, such as when an alias has been defined (more options might be
624 // added at at the time the alias is invoked). We need to verify that the
625 // options in the set m_seen_options are all part of a set that may be used
626 // together, but m_seen_options may be missing some of the "required" options.
628 bool Options::VerifyPartialOptions(CommandReturnObject &result) {
629 bool options_are_valid = false;
631 int num_levels = GetRequiredOptions().size();
633 for (int i = 0; i < num_levels && !options_are_valid; ++i) {
634 // In this case we are treating all options as optional rather than
635 // required. Therefore a set of options is correct if m_seen_options is a
636 // subset of the union of m_required_options and m_optional_options.
638 OptionsSetUnion(GetRequiredOptions()[i], GetOptionalOptions()[i],
640 if (IsASubset(m_seen_options, union_set))
641 options_are_valid = true;
645 return options_are_valid;
648 bool Options::HandleOptionCompletion(CompletionRequest &request,
649 OptionElementVector &opt_element_vector,
650 CommandInterpreter &interpreter) {
651 request.SetWordComplete(true);
653 // For now we just scan the completions to see if the cursor position is in
654 // an option or its argument. Otherwise we'll call HandleArgumentCompletion.
655 // In the future we can use completion to validate options as well if we
658 auto opt_defs = GetDefinitions();
660 std::string cur_opt_std_str = request.GetCursorArgumentPrefix().str();
661 const char *cur_opt_str = cur_opt_std_str.c_str();
663 for (size_t i = 0; i < opt_element_vector.size(); i++) {
664 int opt_pos = opt_element_vector[i].opt_pos;
665 int opt_arg_pos = opt_element_vector[i].opt_arg_pos;
666 int opt_defs_index = opt_element_vector[i].opt_defs_index;
667 if (opt_pos == request.GetCursorIndex()) {
668 // We're completing the option itself.
670 if (opt_defs_index == OptionArgElement::eBareDash) {
671 // We're completing a bare dash. That means all options are open.
672 // FIXME: We should scan the other options provided and only complete
674 // within the option group they belong to.
675 char opt_str[3] = {'-', 'a', '\0'};
677 for (auto &def : opt_defs) {
678 if (!def.short_option)
680 opt_str[1] = def.short_option;
681 request.AddCompletion(opt_str);
685 } else if (opt_defs_index == OptionArgElement::eBareDoubleDash) {
686 std::string full_name("--");
687 for (auto &def : opt_defs) {
688 if (!def.short_option)
691 full_name.erase(full_name.begin() + 2, full_name.end());
692 full_name.append(def.long_option);
693 request.AddCompletion(full_name.c_str());
696 } else if (opt_defs_index != OptionArgElement::eUnrecognizedArg) {
697 // We recognized it, if it an incomplete long option, complete it
698 // anyway (getopt_long_only is happy with shortest unique string, but
699 // it's still a nice thing to do.) Otherwise return The string so the
700 // upper level code will know this is a full match and add the " ".
701 if (cur_opt_str && strlen(cur_opt_str) > 2 && cur_opt_str[0] == '-' &&
702 cur_opt_str[1] == '-' &&
703 strcmp(opt_defs[opt_defs_index].long_option, cur_opt_str) != 0) {
704 std::string full_name("--");
705 full_name.append(opt_defs[opt_defs_index].long_option);
706 request.AddCompletion(full_name.c_str());
709 request.AddCompletion(request.GetCursorArgument());
713 // FIXME - not handling wrong options yet:
714 // Check to see if they are writing a long option & complete it.
715 // I think we will only get in here if the long option table has two
717 // that are not unique up to this point. getopt_long_only does
718 // shortest unique match for long options already.
720 if (cur_opt_str && strlen(cur_opt_str) > 2 && cur_opt_str[0] == '-' &&
721 cur_opt_str[1] == '-') {
722 for (auto &def : opt_defs) {
723 if (!def.long_option)
726 if (strstr(def.long_option, cur_opt_str + 2) == def.long_option) {
727 std::string full_name("--");
728 full_name.append(def.long_option);
729 request.AddCompletion(full_name.c_str());
736 } else if (opt_arg_pos == request.GetCursorIndex()) {
737 // Okay the cursor is on the completion of an argument. See if it has a
738 // completion, otherwise return no matches.
740 CompletionRequest subrequest = request;
741 subrequest.SetCursorCharPosition(subrequest.GetCursorArgument().size());
742 if (opt_defs_index != -1) {
743 HandleOptionArgumentCompletion(subrequest, opt_element_vector, i,
745 request.SetWordComplete(subrequest.GetWordComplete());
748 // No completion callback means no completions...
753 // Not the last element, keep going.
760 bool Options::HandleOptionArgumentCompletion(
761 CompletionRequest &request, OptionElementVector &opt_element_vector,
762 int opt_element_index, CommandInterpreter &interpreter) {
763 auto opt_defs = GetDefinitions();
764 std::unique_ptr<SearchFilter> filter_ap;
766 int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos;
767 int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
769 // See if this is an enumeration type option, and if so complete it here:
771 const auto &enum_values = opt_defs[opt_defs_index].enum_values;
772 if (!enum_values.empty()) {
773 bool return_value = false;
774 std::string match_string(
775 request.GetParsedLine().GetArgumentAtIndex(opt_arg_pos),
776 request.GetParsedLine().GetArgumentAtIndex(opt_arg_pos) +
777 request.GetCursorCharPosition());
779 for (const auto &enum_value : enum_values) {
780 if (strstr(enum_value.string_value, match_string.c_str()) ==
781 enum_value.string_value) {
782 request.AddCompletion(enum_value.string_value);
789 // If this is a source file or symbol type completion, and there is a -shlib
790 // option somewhere in the supplied arguments, then make a search filter for
791 // that shared library.
792 // FIXME: Do we want to also have an "OptionType" so we don't have to match
795 uint32_t completion_mask = opt_defs[opt_defs_index].completion_type;
797 if (completion_mask == 0) {
798 lldb::CommandArgumentType option_arg_type =
799 opt_defs[opt_defs_index].argument_type;
800 if (option_arg_type != eArgTypeNone) {
801 const CommandObject::ArgumentTableEntry *arg_entry =
802 CommandObject::FindArgumentDataByType(
803 opt_defs[opt_defs_index].argument_type);
805 completion_mask = arg_entry->completion_type;
809 if (completion_mask & CommandCompletions::eSourceFileCompletion ||
810 completion_mask & CommandCompletions::eSymbolCompletion) {
811 for (size_t i = 0; i < opt_element_vector.size(); i++) {
812 int cur_defs_index = opt_element_vector[i].opt_defs_index;
814 // trying to use <0 indices will definitely cause problems
815 if (cur_defs_index == OptionArgElement::eUnrecognizedArg ||
816 cur_defs_index == OptionArgElement::eBareDash ||
817 cur_defs_index == OptionArgElement::eBareDoubleDash)
820 int cur_arg_pos = opt_element_vector[i].opt_arg_pos;
821 const char *cur_opt_name = opt_defs[cur_defs_index].long_option;
823 // If this is the "shlib" option and there was an argument provided,
824 // restrict it to that shared library.
825 if (cur_opt_name && strcmp(cur_opt_name, "shlib") == 0 &&
827 const char *module_name =
828 request.GetParsedLine().GetArgumentAtIndex(cur_arg_pos);
830 FileSpec module_spec(module_name);
831 lldb::TargetSP target_sp =
832 interpreter.GetDebugger().GetSelectedTarget();
833 // Search filters require a target...
835 filter_ap.reset(new SearchFilterByModule(target_sp, module_spec));
842 return CommandCompletions::InvokeCommonCompletionCallbacks(
843 interpreter, completion_mask, request, filter_ap.get());
846 void OptionGroupOptions::Append(OptionGroup *group) {
847 auto group_option_defs = group->GetDefinitions();
848 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
849 m_option_infos.push_back(OptionInfo(group, i));
850 m_option_defs.push_back(group_option_defs[i]);
854 const OptionGroup *OptionGroupOptions::GetGroupWithOption(char short_opt) {
855 for (uint32_t i = 0; i < m_option_defs.size(); i++) {
856 OptionDefinition opt_def = m_option_defs[i];
857 if (opt_def.short_option == short_opt)
858 return m_option_infos[i].option_group;
863 void OptionGroupOptions::Append(OptionGroup *group, uint32_t src_mask,
865 auto group_option_defs = group->GetDefinitions();
866 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
867 if (group_option_defs[i].usage_mask & src_mask) {
868 m_option_infos.push_back(OptionInfo(group, i));
869 m_option_defs.push_back(group_option_defs[i]);
870 m_option_defs.back().usage_mask = dst_mask;
875 void OptionGroupOptions::Finalize() {
876 m_did_finalize = true;
879 Status OptionGroupOptions::SetOptionValue(uint32_t option_idx,
880 llvm::StringRef option_value,
881 ExecutionContext *execution_context) {
882 // After calling OptionGroupOptions::Append(...), you must finalize the
883 // groups by calling OptionGroupOptions::Finlize()
884 assert(m_did_finalize);
886 if (option_idx < m_option_infos.size()) {
887 error = m_option_infos[option_idx].option_group->SetOptionValue(
888 m_option_infos[option_idx].option_index, option_value,
892 error.SetErrorString("invalid option index"); // Shouldn't happen...
897 void OptionGroupOptions::OptionParsingStarting(
898 ExecutionContext *execution_context) {
899 std::set<OptionGroup *> group_set;
900 OptionInfos::iterator pos, end = m_option_infos.end();
901 for (pos = m_option_infos.begin(); pos != end; ++pos) {
902 OptionGroup *group = pos->option_group;
903 if (group_set.find(group) == group_set.end()) {
904 group->OptionParsingStarting(execution_context);
905 group_set.insert(group);
910 OptionGroupOptions::OptionParsingFinished(ExecutionContext *execution_context) {
911 std::set<OptionGroup *> group_set;
913 OptionInfos::iterator pos, end = m_option_infos.end();
914 for (pos = m_option_infos.begin(); pos != end; ++pos) {
915 OptionGroup *group = pos->option_group;
916 if (group_set.find(group) == group_set.end()) {
917 error = group->OptionParsingFinished(execution_context);
918 group_set.insert(group);
926 // OptionParser permutes the arguments while processing them, so we create a
927 // temporary array holding to avoid modification of the input arguments. The
928 // options themselves are never modified, but the API expects a char * anyway,
929 // hence the const_cast.
930 static std::vector<char *> GetArgvForParsing(const Args &args) {
931 std::vector<char *> result;
932 // OptionParser always skips the first argument as it is based on getopt().
933 result.push_back(const_cast<char *>("<FAKE-ARG0>"));
934 for (const Args::ArgEntry &entry : args)
935 result.push_back(const_cast<char *>(entry.c_str()));
939 // Given a permuted argument, find it's position in the original Args vector.
940 static Args::const_iterator FindOriginalIter(const char *arg,
941 const Args &original) {
942 return llvm::find_if(
943 original, [arg](const Args::ArgEntry &D) { return D.c_str() == arg; });
946 // Given a permuted argument, find it's index in the original Args vector.
947 static size_t FindOriginalIndex(const char *arg, const Args &original) {
948 return std::distance(original.begin(), FindOriginalIter(arg, original));
951 // Construct a new Args object, consisting of the entries from the original
952 // arguments, but in the permuted order.
953 static Args ReconstituteArgsAfterParsing(llvm::ArrayRef<char *> parsed,
954 const Args &original) {
956 for (const char *arg : parsed) {
957 auto pos = FindOriginalIter(arg, original);
958 assert(pos != original.end());
959 result.AppendArgument(pos->ref, pos->quote);
964 static size_t FindArgumentIndexForOption(const Args &args,
965 const Option &long_option) {
966 std::string short_opt = llvm::formatv("-{0}", char(long_option.val)).str();
967 std::string long_opt =
968 llvm::formatv("--{0}", long_option.definition->long_option);
969 for (const auto &entry : llvm::enumerate(args)) {
970 if (entry.value().ref.startswith(short_opt) ||
971 entry.value().ref.startswith(long_opt))
972 return entry.index();
978 llvm::Expected<Args> Options::ParseAlias(const Args &args,
979 OptionArgVector *option_arg_vector,
980 std::string &input_line) {
983 Option *long_options = GetLongOptions();
985 if (long_options == nullptr) {
986 return llvm::make_error<llvm::StringError>("Invalid long options",
987 llvm::inconvertibleErrorCode());
990 for (i = 0; long_options[i].definition != nullptr; ++i) {
991 if (long_options[i].flag == nullptr) {
992 sstr << (char)long_options[i].val;
993 switch (long_options[i].definition->option_has_arg) {
995 case OptionParser::eNoArgument:
997 case OptionParser::eRequiredArgument:
1000 case OptionParser::eOptionalArgument:
1007 Args args_copy = args;
1008 std::vector<char *> argv = GetArgvForParsing(args);
1010 std::unique_lock<std::mutex> lock;
1011 OptionParser::Prepare(lock);
1014 int long_options_index = -1;
1015 val = OptionParser::Parse(argv.size(), &*argv.begin(), sstr.GetString(),
1016 long_options, &long_options_index);
1022 return llvm::make_error<llvm::StringError>(
1023 "Unknown or ambiguous option", llvm::inconvertibleErrorCode());
1031 // Look up the long option index
1032 if (long_options_index == -1) {
1033 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1034 long_options[j].val;
1036 if (long_options[j].val == val) {
1037 long_options_index = j;
1043 // See if the option takes an argument, and see if one was supplied.
1044 if (long_options_index == -1) {
1045 return llvm::make_error<llvm::StringError>(
1046 llvm::formatv("Invalid option with value '{0}'.", char(val)).str(),
1047 llvm::inconvertibleErrorCode());
1050 StreamString option_str;
1051 option_str.Printf("-%c", val);
1052 const OptionDefinition *def = long_options[long_options_index].definition;
1054 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1056 const char *option_arg = nullptr;
1058 case OptionParser::eRequiredArgument:
1059 if (OptionParser::GetOptionArgument() == nullptr) {
1060 return llvm::make_error<llvm::StringError>(
1061 llvm::formatv("Option '{0}' is missing argument specifier.",
1062 option_str.GetString())
1064 llvm::inconvertibleErrorCode());
1067 case OptionParser::eOptionalArgument:
1068 option_arg = OptionParser::GetOptionArgument();
1070 case OptionParser::eNoArgument:
1073 return llvm::make_error<llvm::StringError>(
1074 llvm::formatv("error with options table; invalid value in has_arg "
1075 "field for option '{0}'.",
1078 llvm::inconvertibleErrorCode());
1081 option_arg = "<no-argument>";
1082 option_arg_vector->emplace_back(option_str.GetString(), has_arg,
1085 // Find option in the argument list; also see if it was supposed to take an
1086 // argument and if one was supplied. Remove option (and argument, if
1087 // given) from the argument list. Also remove them from the
1088 // raw_input_string, if one was passed in.
1090 FindArgumentIndexForOption(args_copy, long_options[long_options_index]);
1091 if (idx == size_t(-1))
1094 if (!input_line.empty()) {
1095 auto tmp_arg = args_copy[idx].ref;
1096 size_t pos = input_line.find(tmp_arg);
1097 if (pos != std::string::npos)
1098 input_line.erase(pos, tmp_arg.size());
1100 args_copy.DeleteArgumentAtIndex(idx);
1101 if ((long_options[long_options_index].definition->option_has_arg !=
1102 OptionParser::eNoArgument) &&
1103 (OptionParser::GetOptionArgument() != nullptr) &&
1104 (idx < args_copy.GetArgumentCount()) &&
1105 (args_copy[idx].ref == OptionParser::GetOptionArgument())) {
1106 if (input_line.size() > 0) {
1107 auto tmp_arg = args_copy[idx].ref;
1108 size_t pos = input_line.find(tmp_arg);
1109 if (pos != std::string::npos)
1110 input_line.erase(pos, tmp_arg.size());
1112 args_copy.DeleteArgumentAtIndex(idx);
1116 return std::move(args_copy);
1119 OptionElementVector Options::ParseForCompletion(const Args &args,
1120 uint32_t cursor_index) {
1121 OptionElementVector option_element_vector;
1123 Option *long_options = GetLongOptions();
1124 option_element_vector.clear();
1126 if (long_options == nullptr)
1127 return option_element_vector;
1129 // Leading : tells getopt to return a : for a missing option argument AND to
1130 // suppress error messages.
1133 for (int i = 0; long_options[i].definition != nullptr; ++i) {
1134 if (long_options[i].flag == nullptr) {
1135 sstr << (char)long_options[i].val;
1136 switch (long_options[i].definition->option_has_arg) {
1138 case OptionParser::eNoArgument:
1140 case OptionParser::eRequiredArgument:
1143 case OptionParser::eOptionalArgument:
1150 std::unique_lock<std::mutex> lock;
1151 OptionParser::Prepare(lock);
1152 OptionParser::EnableError(false);
1155 auto opt_defs = GetDefinitions();
1157 std::vector<char *> dummy_vec = GetArgvForParsing(args);
1159 // I stick an element on the end of the input, because if the last element
1160 // is option that requires an argument, getopt_long_only will freak out.
1161 dummy_vec.push_back(const_cast<char *>("<FAKE-VALUE>"));
1163 bool failed_once = false;
1164 uint32_t dash_dash_pos = -1;
1167 bool missing_argument = false;
1168 int long_options_index = -1;
1170 val = OptionParser::Parse(dummy_vec.size(), &dummy_vec[0], sstr.GetString(),
1171 long_options, &long_options_index);
1174 // When we're completing a "--" which is the last option on line,
1180 // If this is a bare "--" we mark it as such so we can complete it
1181 // successfully later. Handling the "--" is a little tricky, since that
1182 // may mean end of options or arguments, or the user might want to
1183 // complete options by long name. I make this work by checking whether
1184 // the cursor is in the "--" argument, and if so I assume we're
1185 // completing the long option, otherwise I let it pass to
1186 // OptionParser::Parse which will terminate the option parsing. Note, in
1187 // either case we continue parsing the line so we can figure out what
1188 // other options were passed. This will be useful when we come to
1189 // restricting completions based on what other options we've seen on the
1192 if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1194 (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) {
1195 dash_dash_pos = FindOriginalIndex(
1196 dummy_vec[OptionParser::GetOptionIndex() - 1], args);
1197 if (dash_dash_pos == cursor_index) {
1198 option_element_vector.push_back(
1199 OptionArgElement(OptionArgElement::eBareDoubleDash, dash_dash_pos,
1200 OptionArgElement::eBareDoubleDash));
1206 } else if (val == '?') {
1207 option_element_vector.push_back(OptionArgElement(
1208 OptionArgElement::eUnrecognizedArg,
1209 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1211 OptionArgElement::eUnrecognizedArg));
1213 } else if (val == 0) {
1215 } else if (val == ':') {
1216 // This is a missing argument.
1217 val = OptionParser::GetOptionErrorCause();
1218 missing_argument = true;
1223 // Look up the long option index
1224 if (long_options_index == -1) {
1225 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1226 long_options[j].val;
1228 if (long_options[j].val == val) {
1229 long_options_index = j;
1235 // See if the option takes an argument, and see if one was supplied.
1236 if (long_options_index >= 0) {
1237 int opt_defs_index = -1;
1238 for (size_t i = 0; i < opt_defs.size(); i++) {
1239 if (opt_defs[i].short_option != val)
1245 const OptionDefinition *def = long_options[long_options_index].definition;
1247 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1249 case OptionParser::eNoArgument:
1250 option_element_vector.push_back(OptionArgElement(
1252 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1256 case OptionParser::eRequiredArgument:
1257 if (OptionParser::GetOptionArgument() != nullptr) {
1259 if (missing_argument)
1262 arg_index = OptionParser::GetOptionIndex() - 2;
1264 option_element_vector.push_back(OptionArgElement(
1266 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1270 option_element_vector.push_back(OptionArgElement(
1272 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1277 case OptionParser::eOptionalArgument:
1278 if (OptionParser::GetOptionArgument() != nullptr) {
1279 option_element_vector.push_back(OptionArgElement(
1281 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1283 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1286 option_element_vector.push_back(OptionArgElement(
1288 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1290 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1295 // The options table is messed up. Here we'll just continue
1296 option_element_vector.push_back(OptionArgElement(
1297 OptionArgElement::eUnrecognizedArg,
1298 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1300 OptionArgElement::eUnrecognizedArg));
1304 option_element_vector.push_back(OptionArgElement(
1305 OptionArgElement::eUnrecognizedArg,
1306 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1308 OptionArgElement::eUnrecognizedArg));
1312 // Finally we have to handle the case where the cursor index points at a
1313 // single "-". We want to mark that in the option_element_vector, but only
1314 // if it is not after the "--". But it turns out that OptionParser::Parse
1315 // just ignores an isolated "-". So we have to look it up by hand here. We
1316 // only care if it is AT the cursor position. Note, a single quoted dash is
1317 // not the same as a single dash...
1319 const Args::ArgEntry &cursor = args[cursor_index];
1320 if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1321 cursor_index < dash_dash_pos) &&
1322 !cursor.IsQuoted() && cursor.ref == "-") {
1323 option_element_vector.push_back(
1324 OptionArgElement(OptionArgElement::eBareDash, cursor_index,
1325 OptionArgElement::eBareDash));
1327 return option_element_vector;
1330 llvm::Expected<Args> Options::Parse(const Args &args,
1331 ExecutionContext *execution_context,
1332 lldb::PlatformSP platform_sp,
1333 bool require_validation) {
1336 Option *long_options = GetLongOptions();
1337 if (long_options == nullptr) {
1338 return llvm::make_error<llvm::StringError>("Invalid long options.",
1339 llvm::inconvertibleErrorCode());
1342 for (int i = 0; long_options[i].definition != nullptr; ++i) {
1343 if (long_options[i].flag == nullptr) {
1344 if (isprint8(long_options[i].val)) {
1345 sstr << (char)long_options[i].val;
1346 switch (long_options[i].definition->option_has_arg) {
1348 case OptionParser::eNoArgument:
1350 case OptionParser::eRequiredArgument:
1353 case OptionParser::eOptionalArgument:
1360 std::vector<char *> argv = GetArgvForParsing(args);
1361 std::unique_lock<std::mutex> lock;
1362 OptionParser::Prepare(lock);
1365 int long_options_index = -1;
1366 val = OptionParser::Parse(argv.size(), &*argv.begin(), sstr.GetString(),
1367 long_options, &long_options_index);
1371 // Did we get an error?
1373 error.SetErrorStringWithFormat("unknown or ambiguous option");
1376 // The option auto-set itself
1382 // Lookup the long option index
1383 if (long_options_index == -1) {
1384 for (int i = 0; long_options[i].definition || long_options[i].flag ||
1385 long_options[i].val;
1387 if (long_options[i].val == val) {
1388 long_options_index = i;
1393 // Call the callback with the option
1394 if (long_options_index >= 0 &&
1395 long_options[long_options_index].definition) {
1396 const OptionDefinition *def = long_options[long_options_index].definition;
1399 // User did not pass in an explicit platform. Try to grab from the
1400 // execution context.
1401 TargetSP target_sp =
1402 execution_context ? execution_context->GetTargetSP() : TargetSP();
1403 platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
1405 OptionValidator *validator = def->validator;
1407 if (!platform_sp && require_validation) {
1408 // Caller requires validation but we cannot validate as we don't have
1409 // the mandatory platform against which to validate.
1410 return llvm::make_error<llvm::StringError>(
1411 "cannot validate options: no platform available",
1412 llvm::inconvertibleErrorCode());
1415 bool validation_failed = false;
1417 // Ensure we have an execution context, empty or not.
1418 ExecutionContext dummy_context;
1419 ExecutionContext *exe_ctx_p =
1420 execution_context ? execution_context : &dummy_context;
1421 if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
1422 validation_failed = true;
1423 error.SetErrorStringWithFormat("Option \"%s\" invalid. %s",
1425 def->validator->LongConditionString());
1429 // As long as validation didn't fail, we set the option value.
1430 if (!validation_failed)
1432 SetOptionValue(long_options_index,
1433 (def->option_has_arg == OptionParser::eNoArgument)
1435 : OptionParser::GetOptionArgument(),
1438 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
1441 return error.ToError();
1444 argv.erase(argv.begin(), argv.begin() + OptionParser::GetOptionIndex());
1445 return ReconstituteArgsAfterParsing(argv, args);