]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Interpreter/Options.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Interpreter / Options.cpp
1 //===-- Options.cpp ---------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "lldb/Interpreter/Options.h"
11
12 #include <algorithm>
13 #include <bitset>
14 #include <map>
15 #include <set>
16
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"
24
25 using namespace lldb;
26 using namespace lldb_private;
27
28 //-------------------------------------------------------------------------
29 // Options
30 //-------------------------------------------------------------------------
31 Options::Options() : m_getopt_table() { BuildValidOptionSets(); }
32
33 Options::~Options() {}
34
35 void Options::NotifyOptionParsingStarting(ExecutionContext *execution_context) {
36   m_seen_options.clear();
37   // Let the subclass reset its option values
38   OptionParsingStarting(execution_context);
39 }
40
41 Status
42 Options::NotifyOptionParsingFinished(ExecutionContext *execution_context) {
43   return OptionParsingFinished(execution_context);
44 }
45
46 void Options::OptionSeen(int option_idx) { m_seen_options.insert(option_idx); }
47
48 // Returns true is set_a is a subset of set_b;  Otherwise returns false.
49
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;
54
55   // set_a is a subset of set_b if every member of set_a is also a member of
56   // set_b
57
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())
61       is_a_subset = false;
62   }
63
64   return is_a_subset;
65 }
66
67 // Returns the set difference set_a - set_b, i.e. { x | ElementOf (x, set_a) &&
68 // !ElementOf (x, set_b) }
69
70 size_t Options::OptionsSetDiff(const OptionSet &set_a, const OptionSet &set_b,
71                                OptionSet &diffs) {
72   size_t num_diffs = 0;
73   OptionSet::const_iterator pos_a;
74   OptionSet::const_iterator pos_b;
75
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()) {
79       ++num_diffs;
80       diffs.insert(*pos_a);
81     }
82   }
83
84   return num_diffs;
85 }
86
87 // Returns the union of set_a and set_b.  Does not put duplicate members into
88 // the union.
89
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;
94
95   // Put all the elements of set_a into the union.
96
97   for (pos = set_a.begin(); pos != set_a.end(); ++pos)
98     union_set.insert(*pos);
99
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);
105   }
106 }
107
108 bool Options::VerifyOptions(CommandReturnObject &result) {
109   bool options_are_valid = false;
110
111   int num_levels = GetRequiredOptions().size();
112   if (num_levels) {
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
119       // level.
120
121       // Check to see if all of m_required_options[i] are a subset of
122       // m_seen_options
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],
128                        remaining_options);
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;
133       }
134     }
135   } else {
136     options_are_valid = true;
137   }
138
139   if (options_are_valid) {
140     result.SetStatus(eReturnStatusSuccessFinishNoResult);
141   } else {
142     result.AppendError("invalid combination of options for the given command");
143     result.SetStatus(eReturnStatusFailed);
144   }
145
146   return options_are_valid;
147 }
148
149 // This is called in the Options constructor, though we could call it lazily if
150 // that ends up being a performance problem.
151
152 void Options::BuildValidOptionSets() {
153   // Check to see if we already did this.
154   if (m_required_options.size() != 0)
155     return;
156
157   // Check to see if there are any options.
158   int num_options = NumCommandOptions();
159   if (num_options == 0)
160     return;
161
162   auto opt_defs = GetDefinitions();
163   m_required_options.resize(1);
164   m_optional_options.resize(1);
165
166   // First count the number of option sets we've got.  Ignore
167   // LLDB_ALL_OPTION_SETS...
168
169   uint32_t num_option_sets = 0;
170
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)
175         num_option_sets = 1;
176     } else {
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;
181         }
182       }
183     }
184   }
185
186   if (num_option_sets > 0) {
187     m_required_options.resize(num_option_sets);
188     m_optional_options.resize(num_option_sets);
189
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) {
193           if (def.required)
194             m_required_options[j].insert(def.short_option);
195           else
196             m_optional_options[j].insert(def.short_option);
197         }
198       }
199     }
200   }
201 }
202
203 uint32_t Options::NumCommandOptions() { return GetDefinitions().size(); }
204
205 Option *Options::GetLongOptions() {
206   // Check to see if this has already been done.
207   if (m_getopt_table.empty()) {
208     auto defs = GetDefinitions();
209     if (defs.empty())
210       return nullptr;
211
212     std::map<int, uint32_t> option_seen;
213
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;
217
218       m_getopt_table[i].definition = &defs[i];
219       m_getopt_table[i].flag = nullptr;
220       m_getopt_table[i].val = short_opt;
221
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);
228         StreamString strm;
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);
237         else
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);
245       }
246     }
247
248     // getopt_long_only requires a NULL final entry in the table:
249
250     m_getopt_table.back().definition = nullptr;
251     m_getopt_table.back().flag = nullptr;
252     m_getopt_table.back().val = 0;
253   }
254
255   if (m_getopt_table.empty())
256     return nullptr;
257
258   return &m_getopt_table.front();
259 }
260
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.
268
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();
275     if (condition) {
276       actual_text = "[";
277       actual_text.append(condition);
278       actual_text.append("] ");
279     }
280   }
281   actual_text.append(option_def.usage_text);
282
283   // Will it all fit on one line?
284
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());
289     strm.EOL();
290   } else {
291     // We need to break it up into multiple lines.
292
293     int text_width = output_max_columns - strm.GetIndentLevel() - 1;
294     int start = 0;
295     int end = start;
296     int final_end = actual_text.length();
297     int sub_len;
298
299     while (end < final_end) {
300       // Don't start the 'text' on a space, since we're already outputting the
301       // indentation.
302       while ((start < final_end) && (actual_text[start] == ' '))
303         start++;
304
305       end = start + text_width;
306       if (end > final_end)
307         end = final_end;
308       else {
309         // If we're not at the end of the text, make sure we break the line on
310         // white space.
311         while (end > start && actual_text[end] != ' ' &&
312                actual_text[end] != '\t' && actual_text[end] != '\n')
313           end--;
314       }
315
316       sub_len = end - start;
317       if (start != 0)
318         strm.EOL();
319       strm.Indent();
320       assert(start < final_end);
321       assert(start + sub_len <= final_end);
322       strm.Write(actual_text.c_str() + start, sub_len);
323       start = end + 1;
324     }
325     strm.EOL();
326   }
327 }
328
329 bool Options::SupportsLongOption(const char *long_option) {
330   if (!long_option || !long_option[0])
331     return false;
332
333   auto opt_defs = GetDefinitions();
334   if (opt_defs.empty())
335     return false;
336
337   const char *long_option_name = long_option;
338   if (long_option[0] == '-' && long_option[1] == '-')
339     long_option_name += 2;
340
341   for (auto &def : opt_defs) {
342     if (!def.long_option)
343       continue;
344
345     if (strcmp(def.long_option, long_option_name) == 0)
346       return true;
347   }
348
349   return false;
350 }
351
352 enum OptionDisplayType {
353   eDisplayBestOption,
354   eDisplayShortOption,
355   eDisplayLongOption
356 };
357
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;
362
363   if (display_type == eDisplayShortOption && !has_short_option)
364     return false;
365
366   if (header && header[0])
367     strm.PutCString(header);
368
369   if (show_optional && !opt_def.required)
370     strm.PutChar('[');
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);
375   else
376     strm.Printf("--%s", opt_def.long_option);
377   switch (opt_def.option_has_arg) {
378   case OptionParser::eNoArgument:
379     break;
380   case OptionParser::eRequiredArgument:
381     strm.Printf(" <%s>", CommandObject::GetArgumentName(opt_def.argument_type));
382     break;
383
384   case OptionParser::eOptionalArgument:
385     strm.Printf("%s[<%s>]", show_short_option ? "" : "=",
386                 CommandObject::GetArgumentName(opt_def.argument_type));
387     break;
388   }
389   if (show_optional && !opt_def.required)
390     strm.PutChar(']');
391   if (footer && footer[0])
392     strm.PutCString(footer);
393   return true;
394 }
395
396 void Options::GenerateOptionUsage(Stream &strm, CommandObject *cmd,
397                                   uint32_t screen_width) {
398   const bool only_print_args = cmd->IsDashDashCommand();
399
400   auto opt_defs = GetDefinitions();
401   const uint32_t save_indent_level = strm.GetIndentLevel();
402   llvm::StringRef name;
403
404   StreamString arguments_str;
405
406   if (cmd) {
407     name = cmd->GetCommandName();
408     cmd->GetFormattedCommandArguments(arguments_str);
409   } else
410     name = "";
411
412   strm.PutCString("\nCommand Options Usage:\n");
413
414   strm.IndentMore(2);
415
416   // First, show each usage level set of options, e.g. <cmd> [options-for-
417   // level-0]
418   //                                                   <cmd>
419   //                                                   [options-for-level-1]
420   //                                                   etc.
421
422   const uint32_t num_options = NumCommandOptions();
423   if (num_options == 0)
424     return;
425
426   uint32_t num_option_sets = GetRequiredOptions().size();
427
428   uint32_t i;
429
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;
433
434       opt_set_mask = 1 << opt_set;
435       if (opt_set > 0)
436         strm.Printf("\n");
437       strm.Indent(name);
438
439       // Different option sets may require different args.
440       StreamString args_str;
441       if (cmd)
442         cmd->GetFormattedCommandArguments(args_str, opt_set_mask);
443
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
446       // as [-abc]
447
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.
453
454           if (def.required && def.option_has_arg == OptionParser::eNoArgument) {
455             options.insert(def.short_option);
456           }
457         }
458       }
459
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))
467               continue;
468             if (i == 1 && ::isupper(*options_pos))
469               continue;
470             strm << (char)*options_pos;
471           }
472       }
473
474       options.clear();
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.
478
479           if (!def.required &&
480               def.option_has_arg == OptionParser::eNoArgument) {
481             options.insert(def.short_option);
482           }
483         }
484       }
485
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))
493               continue;
494             if (i == 1 && ::isupper(*options_pos))
495               continue;
496             strm << (char)*options_pos;
497           }
498         strm.PutChar(']');
499       }
500
501       // First go through and print the required options (list them up front).
502
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);
507         }
508       }
509
510       // Now go through again, and this time only print the optional options.
511
512       for (auto &def : opt_defs) {
513         if (def.usage_mask & opt_set_mask) {
514           // Add current option to the end of out_stream.
515
516           if (!def.required && def.option_has_arg != OptionParser::eNoArgument)
517             PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm);
518         }
519       }
520
521       if (args_str.GetSize() > 0) {
522         if (cmd->WantsRawCommandString() && !only_print_args)
523           strm.Printf(" --");
524
525         strm << " " << args_str.GetString();
526         if (only_print_args)
527           break;
528       }
529     }
530   }
531
532   if (cmd && (only_print_args || cmd->WantsRawCommandString()) &&
533       arguments_str.GetSize() > 0) {
534     if (!only_print_args)
535       strm.PutChar('\n');
536     strm.Indent(name);
537     strm << " " << arguments_str.GetString();
538   }
539
540   strm.Printf("\n\n");
541
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> )
546     //   help text
547
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.
551
552     std::multimap<int, uint32_t> options_seen;
553     strm.IndentMore(5);
554
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
557     // each option.
558
559     i = 0;
560     for (auto &def : opt_defs)
561       options_seen.insert(std::make_pair(def.short_option, i++));
562
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.
566
567     bool first_option_printed = false;
568
569     for (auto pos : options_seen) {
570       i = pos.second;
571       // Print out the help information for this option.
572
573       // Put a newline separation between arguments
574       if (first_option_printed)
575         strm.EOL();
576       else
577         first_option_printed = true;
578
579       CommandArgumentType arg_type = opt_defs[i].argument_type;
580
581       StreamString arg_name_str;
582       arg_name_str.Printf("<%s>", CommandObject::GetArgumentName(arg_type));
583
584       strm.Indent();
585       if (opt_defs[i].short_option && isprint8(opt_defs[i].short_option)) {
586         PrintOption(opt_defs[i], eDisplayShortOption, nullptr, nullptr, false,
587                     strm);
588         PrintOption(opt_defs[i], eDisplayLongOption, " ( ", " )", false, strm);
589       } else {
590         // Short option is not printable, just print long option
591         PrintOption(opt_defs[i], eDisplayLongOption, nullptr, nullptr, false,
592                     strm);
593       }
594       strm.EOL();
595
596       strm.IndentMore(5);
597
598       if (opt_defs[i].usage_text)
599         OutputFormattedUsageText(strm, opt_defs[i], screen_width);
600       if (!opt_defs[i].enum_values.empty()) {
601         strm.Indent();
602         strm.Printf("Values: ");
603         bool is_first = true;
604         for (const auto &enum_value : opt_defs[i].enum_values) {
605           if (is_first) {
606             strm.Printf("%s", enum_value.string_value);
607             is_first = false;
608           }
609           else
610             strm.Printf(" | %s", enum_value.string_value);
611         }
612         strm.EOL();
613       }
614       strm.IndentLess(5);
615     }
616   }
617
618   // Restore the indent level
619   strm.SetIndentLevel(save_indent_level);
620 }
621
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.
627
628 bool Options::VerifyPartialOptions(CommandReturnObject &result) {
629   bool options_are_valid = false;
630
631   int num_levels = GetRequiredOptions().size();
632   if (num_levels) {
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.
637       OptionSet union_set;
638       OptionsSetUnion(GetRequiredOptions()[i], GetOptionalOptions()[i],
639                       union_set);
640       if (IsASubset(m_seen_options, union_set))
641         options_are_valid = true;
642     }
643   }
644
645   return options_are_valid;
646 }
647
648 bool Options::HandleOptionCompletion(CompletionRequest &request,
649                                      OptionElementVector &opt_element_vector,
650                                      CommandInterpreter &interpreter) {
651   request.SetWordComplete(true);
652
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
656   // want.
657
658   auto opt_defs = GetDefinitions();
659
660   std::string cur_opt_std_str = request.GetCursorArgumentPrefix().str();
661   const char *cur_opt_str = cur_opt_std_str.c_str();
662
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.
669
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
673         // options
674         // within the option group they belong to.
675         char opt_str[3] = {'-', 'a', '\0'};
676
677         for (auto &def : opt_defs) {
678           if (!def.short_option)
679             continue;
680           opt_str[1] = def.short_option;
681           request.AddCompletion(opt_str);
682         }
683
684         return true;
685       } else if (opt_defs_index == OptionArgElement::eBareDoubleDash) {
686         std::string full_name("--");
687         for (auto &def : opt_defs) {
688           if (!def.short_option)
689             continue;
690
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());
694         }
695         return true;
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());
707           return true;
708         } else {
709           request.AddCompletion(request.GetCursorArgument());
710           return true;
711         }
712       } else {
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
716         // elements
717         // that are not unique up to this point.  getopt_long_only does
718         // shortest unique match for long options already.
719
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)
724               continue;
725
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());
730             }
731           }
732         }
733         return true;
734       }
735
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.
739
740       CompletionRequest subrequest = request;
741       subrequest.SetCursorCharPosition(subrequest.GetCursorArgument().size());
742       if (opt_defs_index != -1) {
743         HandleOptionArgumentCompletion(subrequest, opt_element_vector, i,
744                                        interpreter);
745         request.SetWordComplete(subrequest.GetWordComplete());
746         return true;
747       } else {
748         // No completion callback means no completions...
749         return true;
750       }
751
752     } else {
753       // Not the last element, keep going.
754       continue;
755     }
756   }
757   return false;
758 }
759
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;
765
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;
768
769   // See if this is an enumeration type option, and if so complete it here:
770
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());
778
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);
783         return_value = true;
784       }
785     }
786     return return_value;
787   }
788
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
793   // string names?
794
795   uint32_t completion_mask = opt_defs[opt_defs_index].completion_type;
796
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);
804       if (arg_entry)
805         completion_mask = arg_entry->completion_type;
806     }
807   }
808
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;
813
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)
818         continue;
819
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;
822
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 &&
826           cur_arg_pos != -1) {
827         const char *module_name =
828             request.GetParsedLine().GetArgumentAtIndex(cur_arg_pos);
829         if (module_name) {
830           FileSpec module_spec(module_name);
831           lldb::TargetSP target_sp =
832               interpreter.GetDebugger().GetSelectedTarget();
833           // Search filters require a target...
834           if (target_sp)
835             filter_ap.reset(new SearchFilterByModule(target_sp, module_spec));
836         }
837         break;
838       }
839     }
840   }
841
842   return CommandCompletions::InvokeCommonCompletionCallbacks(
843       interpreter, completion_mask, request, filter_ap.get());
844 }
845
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]);
851   }
852 }
853
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;
859   }
860   return nullptr;
861 }
862
863 void OptionGroupOptions::Append(OptionGroup *group, uint32_t src_mask,
864                                 uint32_t dst_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;
871     }
872   }
873 }
874
875 void OptionGroupOptions::Finalize() {
876   m_did_finalize = true;
877 }
878
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);
885   Status error;
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,
889         execution_context);
890
891   } else {
892     error.SetErrorString("invalid option index"); // Shouldn't happen...
893   }
894   return error;
895 }
896
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);
906     }
907   }
908 }
909 Status
910 OptionGroupOptions::OptionParsingFinished(ExecutionContext *execution_context) {
911   std::set<OptionGroup *> group_set;
912   Status error;
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);
919       if (error.Fail())
920         return error;
921     }
922   }
923   return error;
924 }
925
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()));
936   return result;
937 }
938
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; });
944 }
945
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));
949 }
950
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) {
955   Args result;
956   for (const char *arg : parsed) {
957     auto pos = FindOriginalIter(arg, original);
958     assert(pos != original.end());
959     result.AppendArgument(pos->ref, pos->quote);
960   }
961   return result;
962 }
963
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();
973   }
974
975   return size_t(-1);
976 }
977
978 llvm::Expected<Args> Options::ParseAlias(const Args &args,
979                                          OptionArgVector *option_arg_vector,
980                                          std::string &input_line) {
981   StreamString sstr;
982   int i;
983   Option *long_options = GetLongOptions();
984
985   if (long_options == nullptr) {
986     return llvm::make_error<llvm::StringError>("Invalid long options",
987                                                llvm::inconvertibleErrorCode());
988   }
989
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) {
994       default:
995       case OptionParser::eNoArgument:
996         break;
997       case OptionParser::eRequiredArgument:
998         sstr << ":";
999         break;
1000       case OptionParser::eOptionalArgument:
1001         sstr << "::";
1002         break;
1003       }
1004     }
1005   }
1006
1007   Args args_copy = args;
1008   std::vector<char *> argv = GetArgvForParsing(args);
1009
1010   std::unique_lock<std::mutex> lock;
1011   OptionParser::Prepare(lock);
1012   int val;
1013   while (1) {
1014     int long_options_index = -1;
1015     val = OptionParser::Parse(argv.size(), &*argv.begin(), sstr.GetString(),
1016                               long_options, &long_options_index);
1017
1018     if (val == -1)
1019       break;
1020
1021     if (val == '?') {
1022       return llvm::make_error<llvm::StringError>(
1023           "Unknown or ambiguous option", llvm::inconvertibleErrorCode());
1024     }
1025
1026     if (val == 0)
1027       continue;
1028
1029     OptionSeen(val);
1030
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;
1035            ++j) {
1036         if (long_options[j].val == val) {
1037           long_options_index = j;
1038           break;
1039         }
1040       }
1041     }
1042
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());
1048     }
1049
1050     StreamString option_str;
1051     option_str.Printf("-%c", val);
1052     const OptionDefinition *def = long_options[long_options_index].definition;
1053     int has_arg =
1054         (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1055
1056     const char *option_arg = nullptr;
1057     switch (has_arg) {
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())
1063                 .str(),
1064             llvm::inconvertibleErrorCode());
1065       }
1066       LLVM_FALLTHROUGH;
1067     case OptionParser::eOptionalArgument:
1068       option_arg = OptionParser::GetOptionArgument();
1069       LLVM_FALLTHROUGH;
1070     case OptionParser::eNoArgument:
1071       break;
1072     default:
1073       return llvm::make_error<llvm::StringError>(
1074           llvm::formatv("error with options table; invalid value in has_arg "
1075                         "field for option '{0}'.",
1076                         char(val))
1077               .str(),
1078           llvm::inconvertibleErrorCode());
1079     }
1080     if (!option_arg)
1081       option_arg = "<no-argument>";
1082     option_arg_vector->emplace_back(option_str.GetString(), has_arg,
1083                                     option_arg);
1084
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.
1089     size_t idx =
1090         FindArgumentIndexForOption(args_copy, long_options[long_options_index]);
1091     if (idx == size_t(-1))
1092       continue;
1093
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());
1099     }
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());
1111       }
1112       args_copy.DeleteArgumentAtIndex(idx);
1113     }
1114   }
1115
1116   return std::move(args_copy);
1117 }
1118
1119 OptionElementVector Options::ParseForCompletion(const Args &args,
1120                                                 uint32_t cursor_index) {
1121   OptionElementVector option_element_vector;
1122   StreamString sstr;
1123   Option *long_options = GetLongOptions();
1124   option_element_vector.clear();
1125
1126   if (long_options == nullptr)
1127     return option_element_vector;
1128
1129   // Leading : tells getopt to return a : for a missing option argument AND to
1130   // suppress error messages.
1131
1132   sstr << ":";
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) {
1137       default:
1138       case OptionParser::eNoArgument:
1139         break;
1140       case OptionParser::eRequiredArgument:
1141         sstr << ":";
1142         break;
1143       case OptionParser::eOptionalArgument:
1144         sstr << "::";
1145         break;
1146       }
1147     }
1148   }
1149
1150   std::unique_lock<std::mutex> lock;
1151   OptionParser::Prepare(lock);
1152   OptionParser::EnableError(false);
1153
1154   int val;
1155   auto opt_defs = GetDefinitions();
1156
1157   std::vector<char *> dummy_vec = GetArgvForParsing(args);
1158
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>"));
1162
1163   bool failed_once = false;
1164   uint32_t dash_dash_pos = -1;
1165
1166   while (1) {
1167     bool missing_argument = false;
1168     int long_options_index = -1;
1169
1170     val = OptionParser::Parse(dummy_vec.size(), &dummy_vec[0], sstr.GetString(),
1171                               long_options, &long_options_index);
1172
1173     if (val == -1) {
1174       // When we're completing a "--" which is the last option on line,
1175       if (failed_once)
1176         break;
1177
1178       failed_once = true;
1179
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
1190       // line.
1191
1192       if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1193               dummy_vec.size() &&
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));
1201           continue;
1202         } else
1203           break;
1204       } else
1205         break;
1206     } else if (val == '?') {
1207       option_element_vector.push_back(OptionArgElement(
1208           OptionArgElement::eUnrecognizedArg,
1209           FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1210                             args),
1211           OptionArgElement::eUnrecognizedArg));
1212       continue;
1213     } else if (val == 0) {
1214       continue;
1215     } else if (val == ':') {
1216       // This is a missing argument.
1217       val = OptionParser::GetOptionErrorCause();
1218       missing_argument = true;
1219     }
1220
1221     OptionSeen(val);
1222
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;
1227            ++j) {
1228         if (long_options[j].val == val) {
1229           long_options_index = j;
1230           break;
1231         }
1232       }
1233     }
1234
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)
1240           continue;
1241         opt_defs_index = i;
1242         break;
1243       }
1244
1245       const OptionDefinition *def = long_options[long_options_index].definition;
1246       int has_arg =
1247           (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1248       switch (has_arg) {
1249       case OptionParser::eNoArgument:
1250         option_element_vector.push_back(OptionArgElement(
1251             opt_defs_index,
1252             FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1253                               args),
1254             0));
1255         break;
1256       case OptionParser::eRequiredArgument:
1257         if (OptionParser::GetOptionArgument() != nullptr) {
1258           int arg_index;
1259           if (missing_argument)
1260             arg_index = -1;
1261           else
1262             arg_index = OptionParser::GetOptionIndex() - 2;
1263
1264           option_element_vector.push_back(OptionArgElement(
1265               opt_defs_index,
1266               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1267                                 args),
1268               arg_index));
1269         } else {
1270           option_element_vector.push_back(OptionArgElement(
1271               opt_defs_index,
1272               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1273                                 args),
1274               -1));
1275         }
1276         break;
1277       case OptionParser::eOptionalArgument:
1278         if (OptionParser::GetOptionArgument() != nullptr) {
1279           option_element_vector.push_back(OptionArgElement(
1280               opt_defs_index,
1281               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1282                                 args),
1283               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1284                                 args)));
1285         } else {
1286           option_element_vector.push_back(OptionArgElement(
1287               opt_defs_index,
1288               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1289                                 args),
1290               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1291                                 args)));
1292         }
1293         break;
1294       default:
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],
1299                               args),
1300             OptionArgElement::eUnrecognizedArg));
1301         break;
1302       }
1303     } else {
1304       option_element_vector.push_back(OptionArgElement(
1305           OptionArgElement::eUnrecognizedArg,
1306           FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1307                             args),
1308           OptionArgElement::eUnrecognizedArg));
1309     }
1310   }
1311
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...
1318
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));
1326   }
1327   return option_element_vector;
1328 }
1329
1330 llvm::Expected<Args> Options::Parse(const Args &args,
1331                                     ExecutionContext *execution_context,
1332                                     lldb::PlatformSP platform_sp,
1333                                     bool require_validation) {
1334   StreamString sstr;
1335   Status error;
1336   Option *long_options = GetLongOptions();
1337   if (long_options == nullptr) {
1338     return llvm::make_error<llvm::StringError>("Invalid long options.",
1339                                                llvm::inconvertibleErrorCode());
1340   }
1341
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) {
1347         default:
1348         case OptionParser::eNoArgument:
1349           break;
1350         case OptionParser::eRequiredArgument:
1351           sstr << ':';
1352           break;
1353         case OptionParser::eOptionalArgument:
1354           sstr << "::";
1355           break;
1356         }
1357       }
1358     }
1359   }
1360   std::vector<char *> argv = GetArgvForParsing(args);
1361   std::unique_lock<std::mutex> lock;
1362   OptionParser::Prepare(lock);
1363   int val;
1364   while (1) {
1365     int long_options_index = -1;
1366     val = OptionParser::Parse(argv.size(), &*argv.begin(), sstr.GetString(),
1367                               long_options, &long_options_index);
1368     if (val == -1)
1369       break;
1370
1371     // Did we get an error?
1372     if (val == '?') {
1373       error.SetErrorStringWithFormat("unknown or ambiguous option");
1374       break;
1375     }
1376     // The option auto-set itself
1377     if (val == 0)
1378       continue;
1379
1380     OptionSeen(val);
1381
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;
1386            ++i) {
1387         if (long_options[i].val == val) {
1388           long_options_index = i;
1389           break;
1390         }
1391       }
1392     }
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;
1397
1398       if (!platform_sp) {
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();
1404       }
1405       OptionValidator *validator = def->validator;
1406
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());
1413       }
1414
1415       bool validation_failed = false;
1416       if (platform_sp) {
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",
1424                                          def->long_option,
1425                                          def->validator->LongConditionString());
1426         }
1427       }
1428
1429       // As long as validation didn't fail, we set the option value.
1430       if (!validation_failed)
1431         error =
1432             SetOptionValue(long_options_index,
1433                            (def->option_has_arg == OptionParser::eNoArgument)
1434                                ? nullptr
1435                                : OptionParser::GetOptionArgument(),
1436                            execution_context);
1437     } else {
1438       error.SetErrorStringWithFormat("invalid option with value '%i'", val);
1439     }
1440     if (error.Fail())
1441       return error.ToError();
1442   }
1443
1444   argv.erase(argv.begin(), argv.begin() + OptionParser::GetOptionIndex());
1445   return ReconstituteArgsAfterParsing(argv, args);
1446 }