Options.cpp revision 309124
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// C Includes
13// C++ Includes
14#include <algorithm>
15#include <bitset>
16#include <map>
17#include <set>
18
19// Other libraries and framework includes
20// Project includes
21#include "lldb/Interpreter/CommandObject.h"
22#include "lldb/Interpreter/CommandReturnObject.h"
23#include "lldb/Interpreter/CommandCompletions.h"
24#include "lldb/Interpreter/CommandInterpreter.h"
25#include "lldb/Core/StreamString.h"
26#include "lldb/Target/Target.h"
27
28using namespace lldb;
29using namespace lldb_private;
30
31//-------------------------------------------------------------------------
32// Options
33//-------------------------------------------------------------------------
34Options::Options (CommandInterpreter &interpreter) :
35    m_interpreter (interpreter),
36    m_getopt_table ()
37{
38    BuildValidOptionSets();
39}
40
41Options::~Options ()
42{
43}
44
45void
46Options::NotifyOptionParsingStarting ()
47{
48    m_seen_options.clear();
49    // Let the subclass reset its option values
50    OptionParsingStarting ();
51}
52
53Error
54Options::NotifyOptionParsingFinished ()
55{
56    return OptionParsingFinished ();
57}
58
59void
60Options::OptionSeen (int option_idx)
61{
62    m_seen_options.insert (option_idx);
63}
64
65// Returns true is set_a is a subset of set_b;  Otherwise returns false.
66
67bool
68Options::IsASubset (const OptionSet& set_a, const OptionSet& set_b)
69{
70    bool is_a_subset = true;
71    OptionSet::const_iterator pos_a;
72    OptionSet::const_iterator pos_b;
73
74    // set_a is a subset of set_b if every member of set_a is also a member of set_b
75
76    for (pos_a = set_a.begin(); pos_a != set_a.end() && is_a_subset; ++pos_a)
77    {
78        pos_b = set_b.find(*pos_a);
79        if (pos_b == set_b.end())
80            is_a_subset = false;
81    }
82
83    return is_a_subset;
84}
85
86// Returns the set difference set_a - set_b, i.e. { x | ElementOf (x, set_a) && !ElementOf (x, set_b) }
87
88size_t
89Options::OptionsSetDiff (const OptionSet& set_a, const OptionSet& set_b, OptionSet& diffs)
90{
91    size_t num_diffs = 0;
92    OptionSet::const_iterator pos_a;
93    OptionSet::const_iterator pos_b;
94
95    for (pos_a = set_a.begin(); pos_a != set_a.end(); ++pos_a)
96    {
97        pos_b = set_b.find(*pos_a);
98        if (pos_b == set_b.end())
99        {
100            ++num_diffs;
101            diffs.insert(*pos_a);
102        }
103    }
104
105    return num_diffs;
106}
107
108// Returns the union of set_a and set_b.  Does not put duplicate members into the union.
109
110void
111Options::OptionsSetUnion (const OptionSet &set_a, const OptionSet &set_b, OptionSet &union_set)
112{
113    OptionSet::const_iterator pos;
114    OptionSet::iterator pos_union;
115
116    // Put all the elements of set_a into the union.
117
118    for (pos = set_a.begin(); pos != set_a.end(); ++pos)
119        union_set.insert(*pos);
120
121    // Put all the elements of set_b that are not already there into the union.
122    for (pos = set_b.begin(); pos != set_b.end(); ++pos)
123    {
124        pos_union = union_set.find(*pos);
125        if (pos_union == union_set.end())
126            union_set.insert(*pos);
127    }
128}
129
130bool
131Options::VerifyOptions (CommandReturnObject &result)
132{
133    bool options_are_valid = false;
134
135    int num_levels = GetRequiredOptions().size();
136    if (num_levels)
137    {
138        for (int i = 0; i < num_levels && !options_are_valid; ++i)
139        {
140            // This is the correct set of options if:  1). m_seen_options contains all of m_required_options[i]
141            // (i.e. all the required options at this level are a subset of m_seen_options); AND
142            // 2). { m_seen_options - m_required_options[i] is a subset of m_options_options[i] (i.e. all the rest of
143            // m_seen_options are in the set of optional options at this level.
144
145            // Check to see if all of m_required_options[i] are a subset of m_seen_options
146            if (IsASubset (GetRequiredOptions()[i], m_seen_options))
147            {
148                // Construct the set difference: remaining_options = {m_seen_options} - {m_required_options[i]}
149                OptionSet remaining_options;
150                OptionsSetDiff (m_seen_options, GetRequiredOptions()[i], remaining_options);
151                // Check to see if remaining_options is a subset of m_optional_options[i]
152                if (IsASubset (remaining_options, GetOptionalOptions()[i]))
153                    options_are_valid = true;
154            }
155        }
156    }
157    else
158    {
159        options_are_valid = true;
160    }
161
162    if (options_are_valid)
163    {
164        result.SetStatus (eReturnStatusSuccessFinishNoResult);
165    }
166    else
167    {
168        result.AppendError ("invalid combination of options for the given command");
169        result.SetStatus (eReturnStatusFailed);
170    }
171
172    return options_are_valid;
173}
174
175// This is called in the Options constructor, though we could call it lazily if that ends up being
176// a performance problem.
177
178void
179Options::BuildValidOptionSets ()
180{
181    // Check to see if we already did this.
182    if (m_required_options.size() != 0)
183        return;
184
185    // Check to see if there are any options.
186    int num_options = NumCommandOptions ();
187    if (num_options == 0)
188        return;
189
190    const OptionDefinition *opt_defs = GetDefinitions();
191    m_required_options.resize(1);
192    m_optional_options.resize(1);
193
194    // First count the number of option sets we've got.  Ignore LLDB_ALL_OPTION_SETS...
195
196    uint32_t num_option_sets = 0;
197
198    for (int i = 0; i < num_options; i++)
199    {
200        uint32_t this_usage_mask = opt_defs[i].usage_mask;
201        if (this_usage_mask == LLDB_OPT_SET_ALL)
202        {
203            if (num_option_sets == 0)
204                num_option_sets = 1;
205        }
206        else
207        {
208            for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++)
209            {
210                if (this_usage_mask & (1 << j))
211                {
212                    if (num_option_sets <= j)
213                        num_option_sets = j + 1;
214                }
215            }
216        }
217    }
218
219    if (num_option_sets > 0)
220    {
221        m_required_options.resize(num_option_sets);
222        m_optional_options.resize(num_option_sets);
223
224        for (int i = 0; i < num_options; ++i)
225        {
226            for (uint32_t j = 0; j < num_option_sets; j++)
227            {
228                if (opt_defs[i].usage_mask & 1 << j)
229                {
230                    if (opt_defs[i].required)
231                        m_required_options[j].insert(opt_defs[i].short_option);
232                    else
233                        m_optional_options[j].insert(opt_defs[i].short_option);
234                }
235            }
236        }
237    }
238}
239
240uint32_t
241Options::NumCommandOptions ()
242{
243    const OptionDefinition *opt_defs = GetDefinitions ();
244    if (opt_defs == nullptr)
245        return 0;
246
247    int i = 0;
248
249    if (opt_defs != nullptr)
250    {
251        while (opt_defs[i].long_option != nullptr)
252            ++i;
253    }
254
255    return i;
256}
257
258Option *
259Options::GetLongOptions ()
260{
261    // Check to see if this has already been done.
262    if (m_getopt_table.empty())
263    {
264        // Check to see if there are any options.
265        const uint32_t num_options = NumCommandOptions();
266        if (num_options == 0)
267            return nullptr;
268
269        uint32_t i;
270        const OptionDefinition *opt_defs = GetDefinitions();
271
272        std::map<int, uint32_t> option_seen;
273
274        m_getopt_table.resize(num_options + 1);
275        for (i = 0; i < num_options; ++i)
276        {
277            const int short_opt = opt_defs[i].short_option;
278
279            m_getopt_table[i].definition = &opt_defs[i];
280            m_getopt_table[i].flag    = nullptr;
281            m_getopt_table[i].val     = short_opt;
282
283            if (option_seen.find(short_opt) == option_seen.end())
284            {
285                option_seen[short_opt] = i;
286            }
287            else if (short_opt)
288            {
289                m_getopt_table[i].val = 0;
290                std::map<int, uint32_t>::const_iterator pos = option_seen.find(short_opt);
291                StreamString strm;
292                if (isprint8(short_opt))
293                    Host::SystemLog (Host::eSystemLogError, "option[%u] --%s has a short option -%c that conflicts with option[%u] --%s, short option won't be used for --%s\n",
294                                i,
295                                opt_defs[i].long_option,
296                                short_opt,
297                                pos->second,
298                                m_getopt_table[pos->second].definition->long_option,
299                                opt_defs[i].long_option);
300                else
301                    Host::SystemLog (Host::eSystemLogError, "option[%u] --%s has a short option 0x%x that conflicts with option[%u] --%s, short option won't be used for --%s\n",
302                                i,
303                                opt_defs[i].long_option,
304                                short_opt,
305                                pos->second,
306                                m_getopt_table[pos->second].definition->long_option,
307                                opt_defs[i].long_option);
308            }
309        }
310
311        //getopt_long_only requires a NULL final entry in the table:
312
313        m_getopt_table[i].definition    = nullptr;
314        m_getopt_table[i].flag          = nullptr;
315        m_getopt_table[i].val           = 0;
316    }
317
318    if (m_getopt_table.empty())
319        return nullptr;
320
321    return &m_getopt_table.front();
322}
323
324
325// This function takes INDENT, which tells how many spaces to output at the front of each line; SPACES, which is
326// a string containing 80 spaces; and TEXT, which is the text that is to be output.   It outputs the text, on
327// multiple lines if necessary, to RESULT, with INDENT spaces at the front of each line.  It breaks lines on spaces,
328// tabs or newlines, shortening the line if necessary to not break in the middle of a word.  It assumes that each
329// output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
330
331
332void
333Options::OutputFormattedUsageText
334(
335    Stream &strm,
336    const OptionDefinition &option_def,
337    uint32_t output_max_columns
338)
339{
340    std::string actual_text;
341    if (option_def.validator)
342    {
343        const char *condition = option_def.validator->ShortConditionString();
344        if (condition)
345        {
346            actual_text = "[";
347            actual_text.append(condition);
348            actual_text.append("] ");
349        }
350    }
351    actual_text.append(option_def.usage_text);
352
353    // Will it all fit on one line?
354
355    if (static_cast<uint32_t>(actual_text.length() + strm.GetIndentLevel()) < output_max_columns)
356    {
357        // Output it as a single line.
358        strm.Indent (actual_text.c_str());
359        strm.EOL();
360    }
361    else
362    {
363        // We need to break it up into multiple lines.
364
365        int text_width = output_max_columns - strm.GetIndentLevel() - 1;
366        int start = 0;
367        int end = start;
368        int final_end = actual_text.length();
369        int sub_len;
370
371        while (end < final_end)
372        {
373            // Don't start the 'text' on a space, since we're already outputting the indentation.
374            while ((start < final_end) && (actual_text[start] == ' '))
375                start++;
376
377            end = start + text_width;
378            if (end > final_end)
379                end = final_end;
380            else
381            {
382                // If we're not at the end of the text, make sure we break the line on white space.
383                while (end > start
384                       && actual_text[end] != ' ' && actual_text[end] != '\t' && actual_text[end] != '\n')
385                    end--;
386            }
387
388            sub_len = end - start;
389            if (start != 0)
390                strm.EOL();
391            strm.Indent();
392            assert (start < final_end);
393            assert (start + sub_len <= final_end);
394            strm.Write(actual_text.c_str() + start, sub_len);
395            start = end + 1;
396        }
397        strm.EOL();
398    }
399}
400
401bool
402Options::SupportsLongOption (const char *long_option)
403{
404    if (long_option && long_option[0])
405    {
406        const OptionDefinition *opt_defs = GetDefinitions ();
407        if (opt_defs)
408        {
409            const char *long_option_name = long_option;
410            if (long_option[0] == '-' && long_option[1] == '-')
411                long_option_name += 2;
412
413            for (uint32_t i = 0; opt_defs[i].long_option; ++i)
414            {
415                if (strcmp(opt_defs[i].long_option, long_option_name) == 0)
416                    return true;
417            }
418        }
419    }
420    return false;
421}
422
423enum OptionDisplayType
424{
425    eDisplayBestOption,
426    eDisplayShortOption,
427    eDisplayLongOption
428};
429
430static bool
431PrintOption (const OptionDefinition &opt_def,
432             OptionDisplayType display_type,
433             const char *header,
434             const char *footer,
435             bool show_optional,
436             Stream &strm)
437{
438    const bool has_short_option = isprint8(opt_def.short_option) != 0;
439
440    if (display_type == eDisplayShortOption && !has_short_option)
441        return false;
442
443    if (header && header[0])
444        strm.PutCString(header);
445
446    if (show_optional && !opt_def.required)
447    strm.PutChar('[');
448    const bool show_short_option = has_short_option && display_type != eDisplayLongOption;
449    if (show_short_option)
450        strm.Printf ("-%c", opt_def.short_option);
451    else
452        strm.Printf ("--%s", opt_def.long_option);
453    switch (opt_def.option_has_arg)
454    {
455        case OptionParser::eNoArgument:
456            break;
457        case OptionParser::eRequiredArgument:
458            strm.Printf (" <%s>", CommandObject::GetArgumentName (opt_def.argument_type));
459            break;
460
461        case OptionParser::eOptionalArgument:
462            strm.Printf ("%s[<%s>]",
463                         show_short_option ? "" : "=",
464                         CommandObject::GetArgumentName (opt_def.argument_type));
465            break;
466    }
467    if (show_optional && !opt_def.required)
468        strm.PutChar(']');
469    if (footer && footer[0])
470        strm.PutCString(footer);
471    return true;
472}
473
474void
475Options::GenerateOptionUsage
476(
477    Stream &strm,
478    CommandObject *cmd
479)
480{
481    const bool only_print_args = cmd->IsDashDashCommand();
482    const uint32_t screen_width = m_interpreter.GetDebugger().GetTerminalWidth();
483
484    const OptionDefinition *opt_defs = GetDefinitions();
485    const uint32_t save_indent_level = strm.GetIndentLevel();
486    const char *name;
487
488    StreamString arguments_str;
489
490    if (cmd)
491    {
492        name = cmd->GetCommandName();
493        cmd->GetFormattedCommandArguments (arguments_str);
494    }
495    else
496        name = "";
497
498    strm.PutCString ("\nCommand Options Usage:\n");
499
500    strm.IndentMore(2);
501
502    // First, show each usage level set of options, e.g. <cmd> [options-for-level-0]
503    //                                                   <cmd> [options-for-level-1]
504    //                                                   etc.
505
506    const uint32_t num_options = NumCommandOptions();
507    if (num_options == 0)
508        return;
509
510    uint32_t num_option_sets = GetRequiredOptions().size();
511
512    uint32_t i;
513
514    if (!only_print_args)
515    {
516        for (uint32_t opt_set = 0; opt_set < num_option_sets; ++opt_set)
517        {
518            uint32_t opt_set_mask;
519
520            opt_set_mask = 1 << opt_set;
521            if (opt_set > 0)
522                strm.Printf ("\n");
523            strm.Indent (name);
524
525            // Different option sets may require different args.
526            StreamString args_str;
527            if (cmd)
528                cmd->GetFormattedCommandArguments(args_str, opt_set_mask);
529
530            // First go through and print all options that take no arguments as
531            // a single string. If a command has "-a" "-b" and "-c", this will show
532            // up as [-abc]
533
534            std::set<int> options;
535            std::set<int>::const_iterator options_pos, options_end;
536            for (i = 0; i < num_options; ++i)
537            {
538                if (opt_defs[i].usage_mask & opt_set_mask && isprint8(opt_defs[i].short_option))
539                {
540                    // Add current option to the end of out_stream.
541
542                    if (opt_defs[i].required == true &&
543                        opt_defs[i].option_has_arg == OptionParser::eNoArgument)
544                    {
545                        options.insert (opt_defs[i].short_option);
546                    }
547                }
548            }
549
550            if (options.empty() == false)
551            {
552                // We have some required options with no arguments
553                strm.PutCString(" -");
554                for (i=0; i<2; ++i)
555                    for (options_pos = options.begin(), options_end = options.end();
556                         options_pos != options_end;
557                         ++options_pos)
558                    {
559                        if (i==0 && ::islower (*options_pos))
560                            continue;
561                        if (i==1 && ::isupper (*options_pos))
562                            continue;
563                        strm << (char)*options_pos;
564                    }
565            }
566
567            for (i = 0, options.clear(); i < num_options; ++i)
568            {
569                if (opt_defs[i].usage_mask & opt_set_mask && isprint8(opt_defs[i].short_option))
570                {
571                    // Add current option to the end of out_stream.
572
573                    if (opt_defs[i].required == false &&
574                        opt_defs[i].option_has_arg == OptionParser::eNoArgument)
575                    {
576                        options.insert (opt_defs[i].short_option);
577                    }
578                }
579            }
580
581            if (options.empty() == false)
582            {
583                // We have some required options with no arguments
584                strm.PutCString(" [-");
585                for (i=0; i<2; ++i)
586                    for (options_pos = options.begin(), options_end = options.end();
587                         options_pos != options_end;
588                         ++options_pos)
589                    {
590                        if (i==0 && ::islower (*options_pos))
591                            continue;
592                        if (i==1 && ::isupper (*options_pos))
593                            continue;
594                        strm << (char)*options_pos;
595                    }
596                strm.PutChar(']');
597            }
598
599            // First go through and print the required options (list them up front).
600
601            for (i = 0; i < num_options; ++i)
602            {
603                if (opt_defs[i].usage_mask & opt_set_mask && isprint8(opt_defs[i].short_option))
604                {
605                    if (opt_defs[i].required && opt_defs[i].option_has_arg != OptionParser::eNoArgument)
606                        PrintOption (opt_defs[i], eDisplayBestOption, " ", nullptr, true, strm);
607                }
608            }
609
610            // Now go through again, and this time only print the optional options.
611
612            for (i = 0; i < num_options; ++i)
613            {
614                if (opt_defs[i].usage_mask & opt_set_mask)
615                {
616                    // Add current option to the end of out_stream.
617
618                    if (!opt_defs[i].required && opt_defs[i].option_has_arg != OptionParser::eNoArgument)
619                        PrintOption (opt_defs[i], eDisplayBestOption, " ", nullptr, true, strm);
620                }
621            }
622
623            if (args_str.GetSize() > 0)
624            {
625                if (cmd->WantsRawCommandString() && !only_print_args)
626                    strm.Printf(" --");
627
628                strm.Printf (" %s", args_str.GetData());
629                if (only_print_args)
630                    break;
631            }
632        }
633    }
634
635    if (cmd &&
636        (only_print_args || cmd->WantsRawCommandString()) &&
637        arguments_str.GetSize() > 0)
638    {
639        if (!only_print_args) strm.PutChar('\n');
640        strm.Indent(name);
641        strm.Printf(" %s", arguments_str.GetData());
642    }
643
644    strm.Printf ("\n\n");
645
646    if (!only_print_args)
647    {
648        // Now print out all the detailed information about the various options:  long form, short form and help text:
649        //   -short <argument> ( --long_name <argument> )
650        //   help text
651
652        // This variable is used to keep track of which options' info we've printed out, because some options can be in
653        // more than one usage level, but we only want to print the long form of its information once.
654
655        std::multimap<int, uint32_t> options_seen;
656        strm.IndentMore (5);
657
658        // Put the unique command options in a vector & sort it, so we can output them alphabetically (by short_option)
659        // when writing out detailed help for each option.
660
661        for (i = 0; i < num_options; ++i)
662            options_seen.insert(std::make_pair(opt_defs[i].short_option, i));
663
664        // Go through the unique'd and alphabetically sorted vector of options, find the table entry for each option
665        // and write out the detailed help information for that option.
666
667        bool first_option_printed = false;;
668
669        for (auto pos : options_seen)
670        {
671            i = pos.second;
672            //Print out the help information for this option.
673
674            // Put a newline separation between arguments
675            if (first_option_printed)
676                strm.EOL();
677            else
678                first_option_printed = true;
679
680            CommandArgumentType arg_type = opt_defs[i].argument_type;
681
682            StreamString arg_name_str;
683            arg_name_str.Printf ("<%s>", CommandObject::GetArgumentName (arg_type));
684
685            strm.Indent ();
686            if (opt_defs[i].short_option && isprint8(opt_defs[i].short_option))
687            {
688                PrintOption (opt_defs[i], eDisplayShortOption, nullptr, nullptr, false, strm);
689                PrintOption (opt_defs[i], eDisplayLongOption, " ( ", " )", false, strm);
690            }
691            else
692            {
693                // Short option is not printable, just print long option
694                PrintOption (opt_defs[i], eDisplayLongOption, nullptr, nullptr, false, strm);
695            }
696            strm.EOL();
697
698            strm.IndentMore (5);
699
700            if (opt_defs[i].usage_text)
701                OutputFormattedUsageText (strm,
702                                          opt_defs[i],
703                                          screen_width);
704            if (opt_defs[i].enum_values != nullptr)
705            {
706                strm.Indent ();
707                strm.Printf("Values: ");
708                for (int k = 0; opt_defs[i].enum_values[k].string_value != nullptr; k++)
709                {
710                    if (k == 0)
711                        strm.Printf("%s", opt_defs[i].enum_values[k].string_value);
712                    else
713                        strm.Printf(" | %s", opt_defs[i].enum_values[k].string_value);
714                }
715                strm.EOL();
716            }
717            strm.IndentLess (5);
718        }
719    }
720
721    // Restore the indent level
722    strm.SetIndentLevel (save_indent_level);
723}
724
725// This function is called when we have been given a potentially incomplete set of
726// options, such as when an alias has been defined (more options might be added at
727// at the time the alias is invoked).  We need to verify that the options in the set
728// m_seen_options are all part of a set that may be used together, but m_seen_options
729// may be missing some of the "required" options.
730
731bool
732Options::VerifyPartialOptions (CommandReturnObject &result)
733{
734    bool options_are_valid = false;
735
736    int num_levels = GetRequiredOptions().size();
737    if (num_levels)
738      {
739        for (int i = 0; i < num_levels && !options_are_valid; ++i)
740          {
741            // In this case we are treating all options as optional rather than required.
742            // Therefore a set of options is correct if m_seen_options is a subset of the
743            // union of m_required_options and m_optional_options.
744            OptionSet union_set;
745            OptionsSetUnion (GetRequiredOptions()[i], GetOptionalOptions()[i], union_set);
746            if (IsASubset (m_seen_options, union_set))
747                options_are_valid = true;
748          }
749      }
750
751    return options_are_valid;
752}
753
754bool
755Options::HandleOptionCompletion
756(
757    Args &input,
758    OptionElementVector &opt_element_vector,
759    int cursor_index,
760    int char_pos,
761    int match_start_point,
762    int max_return_elements,
763    bool &word_complete,
764    lldb_private::StringList &matches
765)
766{
767    word_complete = true;
768
769    // For now we just scan the completions to see if the cursor position is in
770    // an option or its argument.  Otherwise we'll call HandleArgumentCompletion.
771    // In the future we can use completion to validate options as well if we want.
772
773    const OptionDefinition *opt_defs = GetDefinitions();
774
775    std::string cur_opt_std_str (input.GetArgumentAtIndex(cursor_index));
776    cur_opt_std_str.erase(char_pos);
777    const char *cur_opt_str = cur_opt_std_str.c_str();
778
779    for (size_t i = 0; i < opt_element_vector.size(); i++)
780    {
781        int opt_pos = opt_element_vector[i].opt_pos;
782        int opt_arg_pos = opt_element_vector[i].opt_arg_pos;
783        int opt_defs_index = opt_element_vector[i].opt_defs_index;
784        if (opt_pos == cursor_index)
785        {
786            // We're completing the option itself.
787
788            if (opt_defs_index == OptionArgElement::eBareDash)
789            {
790                // We're completing a bare dash.  That means all options are open.
791                // FIXME: We should scan the other options provided and only complete options
792                // within the option group they belong to.
793                char opt_str[3] = {'-', 'a', '\0'};
794
795                for (int j = 0 ; opt_defs[j].short_option != 0 ; j++)
796                {
797                    opt_str[1] = opt_defs[j].short_option;
798                    matches.AppendString (opt_str);
799                }
800                return true;
801            }
802            else if (opt_defs_index == OptionArgElement::eBareDoubleDash)
803            {
804                std::string full_name ("--");
805                for (int j = 0 ; opt_defs[j].short_option != 0 ; j++)
806                {
807                    full_name.erase(full_name.begin() + 2, full_name.end());
808                    full_name.append (opt_defs[j].long_option);
809                    matches.AppendString (full_name.c_str());
810                }
811                return true;
812            }
813            else if (opt_defs_index != OptionArgElement::eUnrecognizedArg)
814            {
815                // We recognized it, if it an incomplete long option, complete it anyway (getopt_long_only is
816                // happy with shortest unique string, but it's still a nice thing to do.)  Otherwise return
817                // The string so the upper level code will know this is a full match and add the " ".
818                if (cur_opt_str && strlen (cur_opt_str) > 2
819                    && cur_opt_str[0] == '-' && cur_opt_str[1] == '-'
820                    && strcmp (opt_defs[opt_defs_index].long_option, cur_opt_str) != 0)
821                {
822                        std::string full_name ("--");
823                        full_name.append (opt_defs[opt_defs_index].long_option);
824                        matches.AppendString(full_name.c_str());
825                        return true;
826                }
827                else
828                {
829                    matches.AppendString(input.GetArgumentAtIndex(cursor_index));
830                    return true;
831                }
832            }
833            else
834            {
835                // FIXME - not handling wrong options yet:
836                // Check to see if they are writing a long option & complete it.
837                // I think we will only get in here if the long option table has two elements
838                // that are not unique up to this point.  getopt_long_only does shortest unique match
839                // for long options already.
840
841                if (cur_opt_str && strlen (cur_opt_str) > 2
842                    && cur_opt_str[0] == '-' && cur_opt_str[1] == '-')
843                {
844                    for (int j = 0 ; opt_defs[j].short_option != 0 ; j++)
845                    {
846                        if (strstr(opt_defs[j].long_option, cur_opt_str + 2) == opt_defs[j].long_option)
847                        {
848                            std::string full_name ("--");
849                            full_name.append (opt_defs[j].long_option);
850                            // The options definitions table has duplicates because of the
851                            // way the grouping information is stored, so only add once.
852                            bool duplicate = false;
853                            for (size_t k = 0; k < matches.GetSize(); k++)
854                            {
855                                if (matches.GetStringAtIndex(k) == full_name)
856                                {
857                                    duplicate = true;
858                                    break;
859                                }
860                            }
861                            if (!duplicate)
862                                matches.AppendString(full_name.c_str());
863                        }
864                    }
865                }
866                return true;
867            }
868
869
870        }
871        else if (opt_arg_pos == cursor_index)
872        {
873            // Okay the cursor is on the completion of an argument.
874            // See if it has a completion, otherwise return no matches.
875
876            if (opt_defs_index != -1)
877            {
878                HandleOptionArgumentCompletion (input,
879                                                cursor_index,
880                                                strlen (input.GetArgumentAtIndex(cursor_index)),
881                                                opt_element_vector,
882                                                i,
883                                                match_start_point,
884                                                max_return_elements,
885                                                word_complete,
886                                                matches);
887                return true;
888            }
889            else
890            {
891                // No completion callback means no completions...
892                return true;
893            }
894
895        }
896        else
897        {
898            // Not the last element, keep going.
899            continue;
900        }
901    }
902    return false;
903}
904
905bool
906Options::HandleOptionArgumentCompletion
907(
908    Args &input,
909    int cursor_index,
910    int char_pos,
911    OptionElementVector &opt_element_vector,
912    int opt_element_index,
913    int match_start_point,
914    int max_return_elements,
915    bool &word_complete,
916    lldb_private::StringList &matches
917)
918{
919    const OptionDefinition *opt_defs = GetDefinitions();
920    std::unique_ptr<SearchFilter> filter_ap;
921
922    int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos;
923    int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
924
925    // See if this is an enumeration type option, and if so complete it here:
926
927    OptionEnumValueElement *enum_values = opt_defs[opt_defs_index].enum_values;
928    if (enum_values != nullptr)
929    {
930        bool return_value = false;
931        std::string match_string(input.GetArgumentAtIndex (opt_arg_pos), input.GetArgumentAtIndex (opt_arg_pos) + char_pos);
932        for (int i = 0; enum_values[i].string_value != nullptr; i++)
933        {
934            if (strstr(enum_values[i].string_value, match_string.c_str()) == enum_values[i].string_value)
935            {
936                matches.AppendString (enum_values[i].string_value);
937                return_value = true;
938            }
939        }
940        return return_value;
941    }
942
943    // If this is a source file or symbol type completion, and  there is a
944    // -shlib option somewhere in the supplied arguments, then make a search filter
945    // for that shared library.
946    // FIXME: Do we want to also have an "OptionType" so we don't have to match string names?
947
948    uint32_t completion_mask = opt_defs[opt_defs_index].completion_type;
949
950    if (completion_mask == 0)
951    {
952        lldb::CommandArgumentType option_arg_type = opt_defs[opt_defs_index].argument_type;
953        if (option_arg_type != eArgTypeNone)
954        {
955            const CommandObject::ArgumentTableEntry *arg_entry = CommandObject::FindArgumentDataByType (opt_defs[opt_defs_index].argument_type);
956            if (arg_entry)
957                completion_mask = arg_entry->completion_type;
958        }
959    }
960
961    if (completion_mask & CommandCompletions::eSourceFileCompletion
962        || completion_mask & CommandCompletions::eSymbolCompletion)
963    {
964        for (size_t i = 0; i < opt_element_vector.size(); i++)
965        {
966            int cur_defs_index = opt_element_vector[i].opt_defs_index;
967
968            // trying to use <0 indices will definitely cause problems
969            if (cur_defs_index == OptionArgElement::eUnrecognizedArg ||
970                cur_defs_index == OptionArgElement::eBareDash ||
971                cur_defs_index == OptionArgElement::eBareDoubleDash)
972                continue;
973
974            int cur_arg_pos    = opt_element_vector[i].opt_arg_pos;
975            const char *cur_opt_name = opt_defs[cur_defs_index].long_option;
976
977            // If this is the "shlib" option and there was an argument provided,
978            // restrict it to that shared library.
979            if (cur_opt_name && strcmp(cur_opt_name, "shlib") == 0 && cur_arg_pos != -1)
980            {
981                const char *module_name = input.GetArgumentAtIndex(cur_arg_pos);
982                if (module_name)
983                {
984                    FileSpec module_spec(module_name, false);
985                    lldb::TargetSP target_sp = m_interpreter.GetDebugger().GetSelectedTarget();
986                    // Search filters require a target...
987                    if (target_sp)
988                        filter_ap.reset (new SearchFilterByModule (target_sp, module_spec));
989                }
990                break;
991            }
992        }
993    }
994
995    return CommandCompletions::InvokeCommonCompletionCallbacks (m_interpreter,
996                                                                completion_mask,
997                                                                input.GetArgumentAtIndex (opt_arg_pos),
998                                                                match_start_point,
999                                                                max_return_elements,
1000                                                                filter_ap.get(),
1001                                                                word_complete,
1002                                                                matches);
1003
1004}
1005
1006
1007void
1008OptionGroupOptions::Append (OptionGroup* group)
1009{
1010    const OptionDefinition* group_option_defs = group->GetDefinitions ();
1011    const uint32_t group_option_count = group->GetNumDefinitions();
1012    for (uint32_t i=0; i<group_option_count; ++i)
1013    {
1014        m_option_infos.push_back (OptionInfo (group, i));
1015        m_option_defs.push_back (group_option_defs[i]);
1016    }
1017}
1018
1019const OptionGroup*
1020OptionGroupOptions::GetGroupWithOption (char short_opt)
1021{
1022    for (uint32_t i = 0; i < m_option_defs.size(); i++)
1023    {
1024        OptionDefinition opt_def = m_option_defs[i];
1025        if (opt_def.short_option == short_opt)
1026            return m_option_infos[i].option_group;
1027    }
1028    return nullptr;
1029}
1030
1031void
1032OptionGroupOptions::Append (OptionGroup* group,
1033                            uint32_t src_mask,
1034                            uint32_t dst_mask)
1035{
1036    const OptionDefinition* group_option_defs = group->GetDefinitions ();
1037    const uint32_t group_option_count = group->GetNumDefinitions();
1038    for (uint32_t i=0; i<group_option_count; ++i)
1039    {
1040        if (group_option_defs[i].usage_mask & src_mask)
1041        {
1042            m_option_infos.push_back (OptionInfo (group, i));
1043            m_option_defs.push_back (group_option_defs[i]);
1044            m_option_defs.back().usage_mask = dst_mask;
1045        }
1046    }
1047}
1048
1049void
1050OptionGroupOptions::Finalize ()
1051{
1052    m_did_finalize = true;
1053    OptionDefinition empty_option_def = { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr };
1054    m_option_defs.push_back (empty_option_def);
1055}
1056
1057Error
1058OptionGroupOptions::SetOptionValue (uint32_t option_idx,
1059                                    const char *option_value)
1060{
1061    // After calling OptionGroupOptions::Append(...), you must finalize the groups
1062    // by calling OptionGroupOptions::Finlize()
1063    assert (m_did_finalize);
1064    assert (m_option_infos.size() + 1 == m_option_defs.size());
1065    Error error;
1066    if (option_idx < m_option_infos.size())
1067    {
1068        error = m_option_infos[option_idx].option_group->SetOptionValue (m_interpreter,
1069                                                                         m_option_infos[option_idx].option_index,
1070                                                                         option_value);
1071
1072    }
1073    else
1074    {
1075        error.SetErrorString ("invalid option index"); // Shouldn't happen...
1076    }
1077    return error;
1078}
1079
1080void
1081OptionGroupOptions::OptionParsingStarting ()
1082{
1083    std::set<OptionGroup*> group_set;
1084    OptionInfos::iterator pos, end = m_option_infos.end();
1085    for (pos = m_option_infos.begin(); pos != end; ++pos)
1086    {
1087        OptionGroup* group = pos->option_group;
1088        if (group_set.find(group) == group_set.end())
1089        {
1090            group->OptionParsingStarting (m_interpreter);
1091            group_set.insert(group);
1092        }
1093    }
1094}
1095Error
1096OptionGroupOptions::OptionParsingFinished ()
1097{
1098    std::set<OptionGroup*> group_set;
1099    Error error;
1100    OptionInfos::iterator pos, end = m_option_infos.end();
1101    for (pos = m_option_infos.begin(); pos != end; ++pos)
1102    {
1103        OptionGroup* group = pos->option_group;
1104        if (group_set.find(group) == group_set.end())
1105        {
1106            error = group->OptionParsingFinished (m_interpreter);
1107            group_set.insert(group);
1108            if (error.Fail())
1109                return error;
1110        }
1111    }
1112    return error;
1113}
1114