1 //===-- Options.cpp ---------------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Interpreter/Options.h"
16 #include "lldb/Host/OptionParser.h"
17 #include "lldb/Interpreter/CommandCompletions.h"
18 #include "lldb/Interpreter/CommandInterpreter.h"
19 #include "lldb/Interpreter/CommandObject.h"
20 #include "lldb/Interpreter/CommandReturnObject.h"
21 #include "lldb/Target/Target.h"
22 #include "lldb/Utility/StreamString.h"
25 using namespace lldb_private;
28 Options::Options() : m_getopt_table() { BuildValidOptionSets(); }
30 Options::~Options() {}
32 void Options::NotifyOptionParsingStarting(ExecutionContext *execution_context) {
33 m_seen_options.clear();
34 // Let the subclass reset its option values
35 OptionParsingStarting(execution_context);
39 Options::NotifyOptionParsingFinished(ExecutionContext *execution_context) {
40 return OptionParsingFinished(execution_context);
43 void Options::OptionSeen(int option_idx) { m_seen_options.insert(option_idx); }
45 // Returns true is set_a is a subset of set_b; Otherwise returns false.
47 bool Options::IsASubset(const OptionSet &set_a, const OptionSet &set_b) {
48 bool is_a_subset = true;
49 OptionSet::const_iterator pos_a;
50 OptionSet::const_iterator pos_b;
52 // set_a is a subset of set_b if every member of set_a is also a member of
55 for (pos_a = set_a.begin(); pos_a != set_a.end() && is_a_subset; ++pos_a) {
56 pos_b = set_b.find(*pos_a);
57 if (pos_b == set_b.end())
64 // Returns the set difference set_a - set_b, i.e. { x | ElementOf (x, set_a) &&
65 // !ElementOf (x, set_b) }
67 size_t Options::OptionsSetDiff(const OptionSet &set_a, const OptionSet &set_b,
70 OptionSet::const_iterator pos_a;
71 OptionSet::const_iterator pos_b;
73 for (pos_a = set_a.begin(); pos_a != set_a.end(); ++pos_a) {
74 pos_b = set_b.find(*pos_a);
75 if (pos_b == set_b.end()) {
84 // Returns the union of set_a and set_b. Does not put duplicate members into
87 void Options::OptionsSetUnion(const OptionSet &set_a, const OptionSet &set_b,
88 OptionSet &union_set) {
89 OptionSet::const_iterator pos;
90 OptionSet::iterator pos_union;
92 // Put all the elements of set_a into the union.
94 for (pos = set_a.begin(); pos != set_a.end(); ++pos)
95 union_set.insert(*pos);
97 // Put all the elements of set_b that are not already there into the union.
98 for (pos = set_b.begin(); pos != set_b.end(); ++pos) {
99 pos_union = union_set.find(*pos);
100 if (pos_union == union_set.end())
101 union_set.insert(*pos);
105 bool Options::VerifyOptions(CommandReturnObject &result) {
106 bool options_are_valid = false;
108 int num_levels = GetRequiredOptions().size();
110 for (int i = 0; i < num_levels && !options_are_valid; ++i) {
111 // This is the correct set of options if: 1). m_seen_options contains
112 // all of m_required_options[i] (i.e. all the required options at this
113 // level are a subset of m_seen_options); AND 2). { m_seen_options -
114 // m_required_options[i] is a subset of m_options_options[i] (i.e. all
115 // the rest of m_seen_options are in the set of optional options at this
118 // Check to see if all of m_required_options[i] are a subset of
120 if (IsASubset(GetRequiredOptions()[i], m_seen_options)) {
121 // Construct the set difference: remaining_options = {m_seen_options} -
122 // {m_required_options[i]}
123 OptionSet remaining_options;
124 OptionsSetDiff(m_seen_options, GetRequiredOptions()[i],
126 // Check to see if remaining_options is a subset of
127 // m_optional_options[i]
128 if (IsASubset(remaining_options, GetOptionalOptions()[i]))
129 options_are_valid = true;
133 options_are_valid = true;
136 if (options_are_valid) {
137 result.SetStatus(eReturnStatusSuccessFinishNoResult);
139 result.AppendError("invalid combination of options for the given command");
140 result.SetStatus(eReturnStatusFailed);
143 return options_are_valid;
146 // This is called in the Options constructor, though we could call it lazily if
147 // that ends up being a performance problem.
149 void Options::BuildValidOptionSets() {
150 // Check to see if we already did this.
151 if (m_required_options.size() != 0)
154 // Check to see if there are any options.
155 int num_options = NumCommandOptions();
156 if (num_options == 0)
159 auto opt_defs = GetDefinitions();
160 m_required_options.resize(1);
161 m_optional_options.resize(1);
163 // First count the number of option sets we've got. Ignore
164 // LLDB_ALL_OPTION_SETS...
166 uint32_t num_option_sets = 0;
168 for (const auto &def : opt_defs) {
169 uint32_t this_usage_mask = def.usage_mask;
170 if (this_usage_mask == LLDB_OPT_SET_ALL) {
171 if (num_option_sets == 0)
174 for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++) {
175 if (this_usage_mask & (1 << j)) {
176 if (num_option_sets <= j)
177 num_option_sets = j + 1;
183 if (num_option_sets > 0) {
184 m_required_options.resize(num_option_sets);
185 m_optional_options.resize(num_option_sets);
187 for (const auto &def : opt_defs) {
188 for (uint32_t j = 0; j < num_option_sets; j++) {
189 if (def.usage_mask & 1 << j) {
191 m_required_options[j].insert(def.short_option);
193 m_optional_options[j].insert(def.short_option);
200 uint32_t Options::NumCommandOptions() { return GetDefinitions().size(); }
202 Option *Options::GetLongOptions() {
203 // Check to see if this has already been done.
204 if (m_getopt_table.empty()) {
205 auto defs = GetDefinitions();
209 std::map<int, uint32_t> option_seen;
211 m_getopt_table.resize(defs.size() + 1);
212 for (size_t i = 0; i < defs.size(); ++i) {
213 const int short_opt = defs[i].short_option;
215 m_getopt_table[i].definition = &defs[i];
216 m_getopt_table[i].flag = nullptr;
217 m_getopt_table[i].val = short_opt;
219 if (option_seen.find(short_opt) == option_seen.end()) {
220 option_seen[short_opt] = i;
221 } else if (short_opt) {
222 m_getopt_table[i].val = 0;
223 std::map<int, uint32_t>::const_iterator pos =
224 option_seen.find(short_opt);
226 if (isprint8(short_opt))
227 Host::SystemLog(Host::eSystemLogError,
228 "option[%u] --%s has a short option -%c that "
229 "conflicts with option[%u] --%s, short option won't "
230 "be used for --%s\n",
231 (int)i, defs[i].long_option, short_opt, pos->second,
232 m_getopt_table[pos->second].definition->long_option,
233 defs[i].long_option);
235 Host::SystemLog(Host::eSystemLogError,
236 "option[%u] --%s has a short option 0x%x that "
237 "conflicts with option[%u] --%s, short option won't "
238 "be used for --%s\n",
239 (int)i, defs[i].long_option, short_opt, pos->second,
240 m_getopt_table[pos->second].definition->long_option,
241 defs[i].long_option);
245 // getopt_long_only requires a NULL final entry in the table:
247 m_getopt_table.back().definition = nullptr;
248 m_getopt_table.back().flag = nullptr;
249 m_getopt_table.back().val = 0;
252 if (m_getopt_table.empty())
255 return &m_getopt_table.front();
258 // This function takes INDENT, which tells how many spaces to output at the
259 // front of each line; SPACES, which is a string containing 80 spaces; and
260 // TEXT, which is the text that is to be output. It outputs the text, on
261 // multiple lines if necessary, to RESULT, with INDENT spaces at the front of
262 // each line. It breaks lines on spaces, tabs or newlines, shortening the line
263 // if necessary to not break in the middle of a word. It assumes that each
264 // output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
266 void Options::OutputFormattedUsageText(Stream &strm,
267 const OptionDefinition &option_def,
268 uint32_t output_max_columns) {
269 std::string actual_text;
270 if (option_def.validator) {
271 const char *condition = option_def.validator->ShortConditionString();
274 actual_text.append(condition);
275 actual_text.append("] ");
278 actual_text.append(option_def.usage_text);
280 // Will it all fit on one line?
282 if (static_cast<uint32_t>(actual_text.length() + strm.GetIndentLevel()) <
283 output_max_columns) {
284 // Output it as a single line.
285 strm.Indent(actual_text.c_str());
288 // We need to break it up into multiple lines.
290 int text_width = output_max_columns - strm.GetIndentLevel() - 1;
293 int final_end = actual_text.length();
296 while (end < final_end) {
297 // Don't start the 'text' on a space, since we're already outputting the
299 while ((start < final_end) && (actual_text[start] == ' '))
302 end = start + text_width;
306 // If we're not at the end of the text, make sure we break the line on
308 while (end > start && actual_text[end] != ' ' &&
309 actual_text[end] != '\t' && actual_text[end] != '\n')
313 sub_len = end - start;
317 assert(start < final_end);
318 assert(start + sub_len <= final_end);
319 strm.Write(actual_text.c_str() + start, sub_len);
326 bool Options::SupportsLongOption(const char *long_option) {
327 if (!long_option || !long_option[0])
330 auto opt_defs = GetDefinitions();
331 if (opt_defs.empty())
334 const char *long_option_name = long_option;
335 if (long_option[0] == '-' && long_option[1] == '-')
336 long_option_name += 2;
338 for (auto &def : opt_defs) {
339 if (!def.long_option)
342 if (strcmp(def.long_option, long_option_name) == 0)
349 enum OptionDisplayType {
355 static bool PrintOption(const OptionDefinition &opt_def,
356 OptionDisplayType display_type, const char *header,
357 const char *footer, bool show_optional, Stream &strm) {
358 const bool has_short_option = isprint8(opt_def.short_option) != 0;
360 if (display_type == eDisplayShortOption && !has_short_option)
363 if (header && header[0])
364 strm.PutCString(header);
366 if (show_optional && !opt_def.required)
368 const bool show_short_option =
369 has_short_option && display_type != eDisplayLongOption;
370 if (show_short_option)
371 strm.Printf("-%c", opt_def.short_option);
373 strm.Printf("--%s", opt_def.long_option);
374 switch (opt_def.option_has_arg) {
375 case OptionParser::eNoArgument:
377 case OptionParser::eRequiredArgument:
378 strm.Printf(" <%s>", CommandObject::GetArgumentName(opt_def.argument_type));
381 case OptionParser::eOptionalArgument:
382 strm.Printf("%s[<%s>]", show_short_option ? "" : "=",
383 CommandObject::GetArgumentName(opt_def.argument_type));
386 if (show_optional && !opt_def.required)
388 if (footer && footer[0])
389 strm.PutCString(footer);
393 void Options::GenerateOptionUsage(Stream &strm, CommandObject *cmd,
394 uint32_t screen_width) {
395 const bool only_print_args = cmd->IsDashDashCommand();
397 auto opt_defs = GetDefinitions();
398 const uint32_t save_indent_level = strm.GetIndentLevel();
399 llvm::StringRef name;
401 StreamString arguments_str;
404 name = cmd->GetCommandName();
405 cmd->GetFormattedCommandArguments(arguments_str);
409 strm.PutCString("\nCommand Options Usage:\n");
413 // First, show each usage level set of options, e.g. <cmd> [options-for-
416 // [options-for-level-1]
419 const uint32_t num_options = NumCommandOptions();
420 if (num_options == 0)
423 uint32_t num_option_sets = GetRequiredOptions().size();
427 if (!only_print_args) {
428 for (uint32_t opt_set = 0; opt_set < num_option_sets; ++opt_set) {
429 uint32_t opt_set_mask;
431 opt_set_mask = 1 << opt_set;
436 // Different option sets may require different args.
437 StreamString args_str;
439 cmd->GetFormattedCommandArguments(args_str, opt_set_mask);
441 // First go through and print all options that take no arguments as a
442 // single string. If a command has "-a" "-b" and "-c", this will show up
445 std::set<int> options;
446 std::set<int>::const_iterator options_pos, options_end;
447 for (auto &def : opt_defs) {
448 if (def.usage_mask & opt_set_mask && isprint8(def.short_option)) {
449 // Add current option to the end of out_stream.
451 if (def.required && def.option_has_arg == OptionParser::eNoArgument) {
452 options.insert(def.short_option);
457 if (!options.empty()) {
458 // We have some required options with no arguments
459 strm.PutCString(" -");
460 for (i = 0; i < 2; ++i)
461 for (options_pos = options.begin(), options_end = options.end();
462 options_pos != options_end; ++options_pos) {
463 if (i == 0 && ::islower(*options_pos))
465 if (i == 1 && ::isupper(*options_pos))
467 strm << (char)*options_pos;
472 for (auto &def : opt_defs) {
473 if (def.usage_mask & opt_set_mask && isprint8(def.short_option)) {
474 // Add current option to the end of out_stream.
477 def.option_has_arg == OptionParser::eNoArgument) {
478 options.insert(def.short_option);
483 if (!options.empty()) {
484 // We have some required options with no arguments
485 strm.PutCString(" [-");
486 for (i = 0; i < 2; ++i)
487 for (options_pos = options.begin(), options_end = options.end();
488 options_pos != options_end; ++options_pos) {
489 if (i == 0 && ::islower(*options_pos))
491 if (i == 1 && ::isupper(*options_pos))
493 strm << (char)*options_pos;
498 // First go through and print the required options (list them up front).
500 for (auto &def : opt_defs) {
501 if (def.usage_mask & opt_set_mask && isprint8(def.short_option)) {
502 if (def.required && def.option_has_arg != OptionParser::eNoArgument)
503 PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm);
507 // Now go through again, and this time only print the optional options.
509 for (auto &def : opt_defs) {
510 if (def.usage_mask & opt_set_mask) {
511 // Add current option to the end of out_stream.
513 if (!def.required && def.option_has_arg != OptionParser::eNoArgument)
514 PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm);
518 if (args_str.GetSize() > 0) {
519 if (cmd->WantsRawCommandString() && !only_print_args)
522 strm << " " << args_str.GetString();
529 if (cmd && (only_print_args || cmd->WantsRawCommandString()) &&
530 arguments_str.GetSize() > 0) {
531 if (!only_print_args)
534 strm << " " << arguments_str.GetString();
539 if (!only_print_args) {
540 // Now print out all the detailed information about the various options:
541 // long form, short form and help text:
542 // -short <argument> ( --long_name <argument> )
545 // This variable is used to keep track of which options' info we've printed
546 // out, because some options can be in more than one usage level, but we
547 // only want to print the long form of its information once.
549 std::multimap<int, uint32_t> options_seen;
552 // Put the unique command options in a vector & sort it, so we can output
553 // them alphabetically (by short_option) when writing out detailed help for
557 for (auto &def : opt_defs)
558 options_seen.insert(std::make_pair(def.short_option, i++));
560 // Go through the unique'd and alphabetically sorted vector of options,
561 // find the table entry for each option and write out the detailed help
562 // information for that option.
564 bool first_option_printed = false;
566 for (auto pos : options_seen) {
568 // Print out the help information for this option.
570 // Put a newline separation between arguments
571 if (first_option_printed)
574 first_option_printed = true;
576 CommandArgumentType arg_type = opt_defs[i].argument_type;
578 StreamString arg_name_str;
579 arg_name_str.Printf("<%s>", CommandObject::GetArgumentName(arg_type));
582 if (opt_defs[i].short_option && isprint8(opt_defs[i].short_option)) {
583 PrintOption(opt_defs[i], eDisplayShortOption, nullptr, nullptr, false,
585 PrintOption(opt_defs[i], eDisplayLongOption, " ( ", " )", false, strm);
587 // Short option is not printable, just print long option
588 PrintOption(opt_defs[i], eDisplayLongOption, nullptr, nullptr, false,
595 if (opt_defs[i].usage_text)
596 OutputFormattedUsageText(strm, opt_defs[i], screen_width);
597 if (!opt_defs[i].enum_values.empty()) {
599 strm.Printf("Values: ");
600 bool is_first = true;
601 for (const auto &enum_value : opt_defs[i].enum_values) {
603 strm.Printf("%s", enum_value.string_value);
607 strm.Printf(" | %s", enum_value.string_value);
615 // Restore the indent level
616 strm.SetIndentLevel(save_indent_level);
619 // This function is called when we have been given a potentially incomplete set
620 // of options, such as when an alias has been defined (more options might be
621 // added at at the time the alias is invoked). We need to verify that the
622 // options in the set m_seen_options are all part of a set that may be used
623 // together, but m_seen_options may be missing some of the "required" options.
625 bool Options::VerifyPartialOptions(CommandReturnObject &result) {
626 bool options_are_valid = false;
628 int num_levels = GetRequiredOptions().size();
630 for (int i = 0; i < num_levels && !options_are_valid; ++i) {
631 // In this case we are treating all options as optional rather than
632 // required. Therefore a set of options is correct if m_seen_options is a
633 // subset of the union of m_required_options and m_optional_options.
635 OptionsSetUnion(GetRequiredOptions()[i], GetOptionalOptions()[i],
637 if (IsASubset(m_seen_options, union_set))
638 options_are_valid = true;
642 return options_are_valid;
645 bool Options::HandleOptionCompletion(CompletionRequest &request,
646 OptionElementVector &opt_element_vector,
647 CommandInterpreter &interpreter) {
648 // For now we just scan the completions to see if the cursor position is in
649 // an option or its argument. Otherwise we'll call HandleArgumentCompletion.
650 // In the future we can use completion to validate options as well if we
653 auto opt_defs = GetDefinitions();
655 llvm::StringRef cur_opt_str = request.GetCursorArgumentPrefix();
657 for (size_t i = 0; i < opt_element_vector.size(); i++) {
658 size_t opt_pos = static_cast<size_t>(opt_element_vector[i].opt_pos);
659 size_t opt_arg_pos = static_cast<size_t>(opt_element_vector[i].opt_arg_pos);
660 int opt_defs_index = opt_element_vector[i].opt_defs_index;
661 if (opt_pos == request.GetCursorIndex()) {
662 // We're completing the option itself.
664 if (opt_defs_index == OptionArgElement::eBareDash) {
665 // We're completing a bare dash. That means all options are open.
666 // FIXME: We should scan the other options provided and only complete
668 // within the option group they belong to.
669 std::string opt_str = "-a";
671 for (auto &def : opt_defs) {
672 if (!def.short_option)
674 opt_str[1] = def.short_option;
675 request.AddCompletion(opt_str, def.usage_text);
679 } else if (opt_defs_index == OptionArgElement::eBareDoubleDash) {
680 std::string full_name("--");
681 for (auto &def : opt_defs) {
682 if (!def.short_option)
685 full_name.erase(full_name.begin() + 2, full_name.end());
686 full_name.append(def.long_option);
687 request.AddCompletion(full_name, def.usage_text);
690 } else if (opt_defs_index != OptionArgElement::eUnrecognizedArg) {
691 // We recognized it, if it an incomplete long option, complete it
692 // anyway (getopt_long_only is happy with shortest unique string, but
693 // it's still a nice thing to do.) Otherwise return The string so the
694 // upper level code will know this is a full match and add the " ".
695 const OptionDefinition &opt = opt_defs[opt_defs_index];
696 llvm::StringRef long_option = opt.long_option;
697 if (cur_opt_str.startswith("--") && cur_opt_str != long_option) {
698 request.AddCompletion("--" + long_option.str(), opt.usage_text);
701 request.AddCompletion(request.GetCursorArgumentPrefix());
704 // FIXME - not handling wrong options yet:
705 // Check to see if they are writing a long option & complete it.
706 // I think we will only get in here if the long option table has two
708 // that are not unique up to this point. getopt_long_only does
709 // shortest unique match for long options already.
710 if (cur_opt_str.consume_front("--")) {
711 for (auto &def : opt_defs) {
712 llvm::StringRef long_option(def.long_option);
713 if (long_option.startswith(cur_opt_str))
714 request.AddCompletion("--" + long_option.str(), def.usage_text);
720 } else if (opt_arg_pos == request.GetCursorIndex()) {
721 // Okay the cursor is on the completion of an argument. See if it has a
722 // completion, otherwise return no matches.
723 if (opt_defs_index != -1) {
724 HandleOptionArgumentCompletion(request, opt_element_vector, i,
728 // No completion callback means no completions...
733 // Not the last element, keep going.
740 void Options::HandleOptionArgumentCompletion(
741 CompletionRequest &request, OptionElementVector &opt_element_vector,
742 int opt_element_index, CommandInterpreter &interpreter) {
743 auto opt_defs = GetDefinitions();
744 std::unique_ptr<SearchFilter> filter_up;
746 int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
748 // See if this is an enumeration type option, and if so complete it here:
750 const auto &enum_values = opt_defs[opt_defs_index].enum_values;
751 if (!enum_values.empty())
752 for (const auto &enum_value : enum_values)
753 request.TryCompleteCurrentArg(enum_value.string_value);
755 // If this is a source file or symbol type completion, and there is a -shlib
756 // option somewhere in the supplied arguments, then make a search filter for
757 // that shared library.
758 // FIXME: Do we want to also have an "OptionType" so we don't have to match
761 uint32_t completion_mask = opt_defs[opt_defs_index].completion_type;
763 if (completion_mask == 0) {
764 lldb::CommandArgumentType option_arg_type =
765 opt_defs[opt_defs_index].argument_type;
766 if (option_arg_type != eArgTypeNone) {
767 const CommandObject::ArgumentTableEntry *arg_entry =
768 CommandObject::FindArgumentDataByType(
769 opt_defs[opt_defs_index].argument_type);
771 completion_mask = arg_entry->completion_type;
775 if (completion_mask & CommandCompletions::eSourceFileCompletion ||
776 completion_mask & CommandCompletions::eSymbolCompletion) {
777 for (size_t i = 0; i < opt_element_vector.size(); i++) {
778 int cur_defs_index = opt_element_vector[i].opt_defs_index;
780 // trying to use <0 indices will definitely cause problems
781 if (cur_defs_index == OptionArgElement::eUnrecognizedArg ||
782 cur_defs_index == OptionArgElement::eBareDash ||
783 cur_defs_index == OptionArgElement::eBareDoubleDash)
786 int cur_arg_pos = opt_element_vector[i].opt_arg_pos;
787 const char *cur_opt_name = opt_defs[cur_defs_index].long_option;
789 // If this is the "shlib" option and there was an argument provided,
790 // restrict it to that shared library.
791 if (cur_opt_name && strcmp(cur_opt_name, "shlib") == 0 &&
793 const char *module_name =
794 request.GetParsedLine().GetArgumentAtIndex(cur_arg_pos);
796 FileSpec module_spec(module_name);
797 lldb::TargetSP target_sp =
798 interpreter.GetDebugger().GetSelectedTarget();
799 // Search filters require a target...
801 filter_up.reset(new SearchFilterByModule(target_sp, module_spec));
808 CommandCompletions::InvokeCommonCompletionCallbacks(
809 interpreter, completion_mask, request, filter_up.get());
812 void OptionGroupOptions::Append(OptionGroup *group) {
813 auto group_option_defs = group->GetDefinitions();
814 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
815 m_option_infos.push_back(OptionInfo(group, i));
816 m_option_defs.push_back(group_option_defs[i]);
820 const OptionGroup *OptionGroupOptions::GetGroupWithOption(char short_opt) {
821 for (uint32_t i = 0; i < m_option_defs.size(); i++) {
822 OptionDefinition opt_def = m_option_defs[i];
823 if (opt_def.short_option == short_opt)
824 return m_option_infos[i].option_group;
829 void OptionGroupOptions::Append(OptionGroup *group, uint32_t src_mask,
831 auto group_option_defs = group->GetDefinitions();
832 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
833 if (group_option_defs[i].usage_mask & src_mask) {
834 m_option_infos.push_back(OptionInfo(group, i));
835 m_option_defs.push_back(group_option_defs[i]);
836 m_option_defs.back().usage_mask = dst_mask;
841 void OptionGroupOptions::Finalize() {
842 m_did_finalize = true;
845 Status OptionGroupOptions::SetOptionValue(uint32_t option_idx,
846 llvm::StringRef option_value,
847 ExecutionContext *execution_context) {
848 // After calling OptionGroupOptions::Append(...), you must finalize the
849 // groups by calling OptionGroupOptions::Finlize()
850 assert(m_did_finalize);
852 if (option_idx < m_option_infos.size()) {
853 error = m_option_infos[option_idx].option_group->SetOptionValue(
854 m_option_infos[option_idx].option_index, option_value,
858 error.SetErrorString("invalid option index"); // Shouldn't happen...
863 void OptionGroupOptions::OptionParsingStarting(
864 ExecutionContext *execution_context) {
865 std::set<OptionGroup *> group_set;
866 OptionInfos::iterator pos, end = m_option_infos.end();
867 for (pos = m_option_infos.begin(); pos != end; ++pos) {
868 OptionGroup *group = pos->option_group;
869 if (group_set.find(group) == group_set.end()) {
870 group->OptionParsingStarting(execution_context);
871 group_set.insert(group);
876 OptionGroupOptions::OptionParsingFinished(ExecutionContext *execution_context) {
877 std::set<OptionGroup *> group_set;
879 OptionInfos::iterator pos, end = m_option_infos.end();
880 for (pos = m_option_infos.begin(); pos != end; ++pos) {
881 OptionGroup *group = pos->option_group;
882 if (group_set.find(group) == group_set.end()) {
883 error = group->OptionParsingFinished(execution_context);
884 group_set.insert(group);
892 // OptionParser permutes the arguments while processing them, so we create a
893 // temporary array holding to avoid modification of the input arguments. The
894 // options themselves are never modified, but the API expects a char * anyway,
895 // hence the const_cast.
896 static std::vector<char *> GetArgvForParsing(const Args &args) {
897 std::vector<char *> result;
898 // OptionParser always skips the first argument as it is based on getopt().
899 result.push_back(const_cast<char *>("<FAKE-ARG0>"));
900 for (const Args::ArgEntry &entry : args)
901 result.push_back(const_cast<char *>(entry.c_str()));
902 result.push_back(nullptr);
906 // Given a permuted argument, find it's position in the original Args vector.
907 static Args::const_iterator FindOriginalIter(const char *arg,
908 const Args &original) {
909 return llvm::find_if(
910 original, [arg](const Args::ArgEntry &D) { return D.c_str() == arg; });
913 // Given a permuted argument, find it's index in the original Args vector.
914 static size_t FindOriginalIndex(const char *arg, const Args &original) {
915 return std::distance(original.begin(), FindOriginalIter(arg, original));
918 // Construct a new Args object, consisting of the entries from the original
919 // arguments, but in the permuted order.
920 static Args ReconstituteArgsAfterParsing(llvm::ArrayRef<char *> parsed,
921 const Args &original) {
923 for (const char *arg : parsed) {
924 auto pos = FindOriginalIter(arg, original);
925 assert(pos != original.end());
926 result.AppendArgument(pos->ref(), pos->GetQuoteChar());
931 static size_t FindArgumentIndexForOption(const Args &args,
932 const Option &long_option) {
933 std::string short_opt = llvm::formatv("-{0}", char(long_option.val)).str();
934 std::string long_opt =
935 llvm::formatv("--{0}", long_option.definition->long_option);
936 for (const auto &entry : llvm::enumerate(args)) {
937 if (entry.value().ref().startswith(short_opt) ||
938 entry.value().ref().startswith(long_opt))
939 return entry.index();
945 static std::string BuildShortOptions(const Option *long_options) {
947 llvm::raw_string_ostream sstr(storage);
949 // Leading : tells getopt to return a : for a missing option argument AND to
950 // suppress error messages.
953 for (size_t i = 0; long_options[i].definition != nullptr; ++i) {
954 if (long_options[i].flag == nullptr) {
955 sstr << (char)long_options[i].val;
956 switch (long_options[i].definition->option_has_arg) {
958 case OptionParser::eNoArgument:
960 case OptionParser::eRequiredArgument:
963 case OptionParser::eOptionalArgument:
969 return std::move(sstr.str());
972 llvm::Expected<Args> Options::ParseAlias(const Args &args,
973 OptionArgVector *option_arg_vector,
974 std::string &input_line) {
975 Option *long_options = GetLongOptions();
977 if (long_options == nullptr) {
978 return llvm::make_error<llvm::StringError>("Invalid long options",
979 llvm::inconvertibleErrorCode());
982 std::string short_options = BuildShortOptions(long_options);
984 Args args_copy = args;
985 std::vector<char *> argv = GetArgvForParsing(args);
987 std::unique_lock<std::mutex> lock;
988 OptionParser::Prepare(lock);
991 int long_options_index = -1;
992 val = OptionParser::Parse(argv, short_options, long_options,
993 &long_options_index);
996 return llvm::createStringError(llvm::inconvertibleErrorCode(),
997 "last option requires an argument");
1004 return llvm::make_error<llvm::StringError>(
1005 "Unknown or ambiguous option", llvm::inconvertibleErrorCode());
1013 // Look up the long option index
1014 if (long_options_index == -1) {
1015 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1016 long_options[j].val;
1018 if (long_options[j].val == val) {
1019 long_options_index = j;
1025 // See if the option takes an argument, and see if one was supplied.
1026 if (long_options_index == -1) {
1027 return llvm::make_error<llvm::StringError>(
1028 llvm::formatv("Invalid option with value '{0}'.", char(val)).str(),
1029 llvm::inconvertibleErrorCode());
1032 StreamString option_str;
1033 option_str.Printf("-%c", val);
1034 const OptionDefinition *def = long_options[long_options_index].definition;
1036 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1038 const char *option_arg = nullptr;
1040 case OptionParser::eRequiredArgument:
1041 if (OptionParser::GetOptionArgument() == nullptr) {
1042 return llvm::make_error<llvm::StringError>(
1043 llvm::formatv("Option '{0}' is missing argument specifier.",
1044 option_str.GetString())
1046 llvm::inconvertibleErrorCode());
1049 case OptionParser::eOptionalArgument:
1050 option_arg = OptionParser::GetOptionArgument();
1052 case OptionParser::eNoArgument:
1055 return llvm::make_error<llvm::StringError>(
1056 llvm::formatv("error with options table; invalid value in has_arg "
1057 "field for option '{0}'.",
1060 llvm::inconvertibleErrorCode());
1063 option_arg = "<no-argument>";
1064 option_arg_vector->emplace_back(std::string(option_str.GetString()),
1065 has_arg, std::string(option_arg));
1067 // Find option in the argument list; also see if it was supposed to take an
1068 // argument and if one was supplied. Remove option (and argument, if
1069 // given) from the argument list. Also remove them from the
1070 // raw_input_string, if one was passed in.
1072 FindArgumentIndexForOption(args_copy, long_options[long_options_index]);
1073 if (idx == size_t(-1))
1076 if (!input_line.empty()) {
1077 auto tmp_arg = args_copy[idx].ref();
1078 size_t pos = input_line.find(tmp_arg);
1079 if (pos != std::string::npos)
1080 input_line.erase(pos, tmp_arg.size());
1082 args_copy.DeleteArgumentAtIndex(idx);
1083 if ((long_options[long_options_index].definition->option_has_arg !=
1084 OptionParser::eNoArgument) &&
1085 (OptionParser::GetOptionArgument() != nullptr) &&
1086 (idx < args_copy.GetArgumentCount()) &&
1087 (args_copy[idx].ref() == OptionParser::GetOptionArgument())) {
1088 if (input_line.size() > 0) {
1089 auto tmp_arg = args_copy[idx].ref();
1090 size_t pos = input_line.find(tmp_arg);
1091 if (pos != std::string::npos)
1092 input_line.erase(pos, tmp_arg.size());
1094 args_copy.DeleteArgumentAtIndex(idx);
1098 return std::move(args_copy);
1101 OptionElementVector Options::ParseForCompletion(const Args &args,
1102 uint32_t cursor_index) {
1103 OptionElementVector option_element_vector;
1104 Option *long_options = GetLongOptions();
1105 option_element_vector.clear();
1107 if (long_options == nullptr)
1108 return option_element_vector;
1110 std::string short_options = BuildShortOptions(long_options);
1112 std::unique_lock<std::mutex> lock;
1113 OptionParser::Prepare(lock);
1114 OptionParser::EnableError(false);
1117 auto opt_defs = GetDefinitions();
1119 std::vector<char *> dummy_vec = GetArgvForParsing(args);
1121 bool failed_once = false;
1122 uint32_t dash_dash_pos = -1;
1125 bool missing_argument = false;
1126 int long_options_index = -1;
1128 val = OptionParser::Parse(dummy_vec, short_options, long_options,
1129 &long_options_index);
1132 // When we're completing a "--" which is the last option on line,
1138 // If this is a bare "--" we mark it as such so we can complete it
1139 // successfully later. Handling the "--" is a little tricky, since that
1140 // may mean end of options or arguments, or the user might want to
1141 // complete options by long name. I make this work by checking whether
1142 // the cursor is in the "--" argument, and if so I assume we're
1143 // completing the long option, otherwise I let it pass to
1144 // OptionParser::Parse which will terminate the option parsing. Note, in
1145 // either case we continue parsing the line so we can figure out what
1146 // other options were passed. This will be useful when we come to
1147 // restricting completions based on what other options we've seen on the
1150 if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1152 (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) {
1153 dash_dash_pos = FindOriginalIndex(
1154 dummy_vec[OptionParser::GetOptionIndex() - 1], args);
1155 if (dash_dash_pos == cursor_index) {
1156 option_element_vector.push_back(
1157 OptionArgElement(OptionArgElement::eBareDoubleDash, dash_dash_pos,
1158 OptionArgElement::eBareDoubleDash));
1164 } else if (val == '?') {
1165 option_element_vector.push_back(OptionArgElement(
1166 OptionArgElement::eUnrecognizedArg,
1167 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1169 OptionArgElement::eUnrecognizedArg));
1171 } else if (val == 0) {
1173 } else if (val == ':') {
1174 // This is a missing argument.
1175 val = OptionParser::GetOptionErrorCause();
1176 missing_argument = true;
1181 // Look up the long option index
1182 if (long_options_index == -1) {
1183 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1184 long_options[j].val;
1186 if (long_options[j].val == val) {
1187 long_options_index = j;
1193 // See if the option takes an argument, and see if one was supplied.
1194 if (long_options_index >= 0) {
1195 int opt_defs_index = -1;
1196 for (size_t i = 0; i < opt_defs.size(); i++) {
1197 if (opt_defs[i].short_option != val)
1203 const OptionDefinition *def = long_options[long_options_index].definition;
1205 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1207 case OptionParser::eNoArgument:
1208 option_element_vector.push_back(OptionArgElement(
1210 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1214 case OptionParser::eRequiredArgument:
1215 if (OptionParser::GetOptionArgument() != nullptr) {
1217 if (missing_argument)
1220 arg_index = OptionParser::GetOptionIndex() - 2;
1222 option_element_vector.push_back(OptionArgElement(
1224 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1228 option_element_vector.push_back(OptionArgElement(
1230 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1235 case OptionParser::eOptionalArgument:
1236 if (OptionParser::GetOptionArgument() != nullptr) {
1237 option_element_vector.push_back(OptionArgElement(
1239 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1241 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1244 option_element_vector.push_back(OptionArgElement(
1246 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1248 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1253 // The options table is messed up. Here we'll just continue
1254 option_element_vector.push_back(OptionArgElement(
1255 OptionArgElement::eUnrecognizedArg,
1256 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1258 OptionArgElement::eUnrecognizedArg));
1262 option_element_vector.push_back(OptionArgElement(
1263 OptionArgElement::eUnrecognizedArg,
1264 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1266 OptionArgElement::eUnrecognizedArg));
1270 // Finally we have to handle the case where the cursor index points at a
1271 // single "-". We want to mark that in the option_element_vector, but only
1272 // if it is not after the "--". But it turns out that OptionParser::Parse
1273 // just ignores an isolated "-". So we have to look it up by hand here. We
1274 // only care if it is AT the cursor position. Note, a single quoted dash is
1275 // not the same as a single dash...
1277 const Args::ArgEntry &cursor = args[cursor_index];
1278 if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1279 cursor_index < dash_dash_pos) &&
1280 !cursor.IsQuoted() && cursor.ref() == "-") {
1281 option_element_vector.push_back(
1282 OptionArgElement(OptionArgElement::eBareDash, cursor_index,
1283 OptionArgElement::eBareDash));
1285 return option_element_vector;
1288 llvm::Expected<Args> Options::Parse(const Args &args,
1289 ExecutionContext *execution_context,
1290 lldb::PlatformSP platform_sp,
1291 bool require_validation) {
1293 Option *long_options = GetLongOptions();
1294 if (long_options == nullptr) {
1295 return llvm::make_error<llvm::StringError>("Invalid long options.",
1296 llvm::inconvertibleErrorCode());
1299 std::string short_options = BuildShortOptions(long_options);
1300 std::vector<char *> argv = GetArgvForParsing(args);
1301 std::unique_lock<std::mutex> lock;
1302 OptionParser::Prepare(lock);
1305 int long_options_index = -1;
1306 val = OptionParser::Parse(argv, short_options, long_options,
1307 &long_options_index);
1310 error.SetErrorStringWithFormat("last option requires an argument");
1317 // Did we get an error?
1319 error.SetErrorStringWithFormat("unknown or ambiguous option");
1322 // The option auto-set itself
1328 // Lookup the long option index
1329 if (long_options_index == -1) {
1330 for (int i = 0; long_options[i].definition || long_options[i].flag ||
1331 long_options[i].val;
1333 if (long_options[i].val == val) {
1334 long_options_index = i;
1339 // Call the callback with the option
1340 if (long_options_index >= 0 &&
1341 long_options[long_options_index].definition) {
1342 const OptionDefinition *def = long_options[long_options_index].definition;
1345 // User did not pass in an explicit platform. Try to grab from the
1346 // execution context.
1347 TargetSP target_sp =
1348 execution_context ? execution_context->GetTargetSP() : TargetSP();
1349 platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
1351 OptionValidator *validator = def->validator;
1353 if (!platform_sp && require_validation) {
1354 // Caller requires validation but we cannot validate as we don't have
1355 // the mandatory platform against which to validate.
1356 return llvm::make_error<llvm::StringError>(
1357 "cannot validate options: no platform available",
1358 llvm::inconvertibleErrorCode());
1361 bool validation_failed = false;
1363 // Ensure we have an execution context, empty or not.
1364 ExecutionContext dummy_context;
1365 ExecutionContext *exe_ctx_p =
1366 execution_context ? execution_context : &dummy_context;
1367 if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
1368 validation_failed = true;
1369 error.SetErrorStringWithFormat("Option \"%s\" invalid. %s",
1371 def->validator->LongConditionString());
1375 // As long as validation didn't fail, we set the option value.
1376 if (!validation_failed)
1378 SetOptionValue(long_options_index,
1379 (def->option_has_arg == OptionParser::eNoArgument)
1381 : OptionParser::GetOptionArgument(),
1383 // If the Option setting returned an error, we should stop parsing
1384 // and return the error.
1388 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
1393 return error.ToError();
1396 argv.erase(argv.begin(), argv.begin() + OptionParser::GetOptionIndex());
1397 return ReconstituteArgsAfterParsing(argv, args);