blob: 91f1a5f937d4fcdb52904272a8a931f690dc615c [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- 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
Jim Ingham40af72e2010-06-15 19:49:27 +000010#include "lldb/Interpreter/Options.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000011
12// C Includes
13// C++ Includes
Caroline Ticef362c452010-09-09 16:44:14 +000014#include <algorithm>
Greg Claytonab65b342011-04-13 22:47:15 +000015#include <bitset>
Greg Clayton3bcdfc02012-12-04 00:32:51 +000016#include <map>
Enrico Granatabef55ac2016-03-14 22:17:04 +000017#include <set>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018
19// Other libraries and framework includes
20// Project includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000021#include "lldb/Core/StreamString.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Interpreter/CommandCompletions.h"
23#include "lldb/Interpreter/CommandInterpreter.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000024#include "lldb/Interpreter/CommandObject.h"
25#include "lldb/Interpreter/CommandReturnObject.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026#include "lldb/Target/Target.h"
27
28using namespace lldb;
29using namespace lldb_private;
30
31//-------------------------------------------------------------------------
32// Options
33//-------------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000034Options::Options() : m_getopt_table() { BuildValidOptionSets(); }
35
36Options::~Options() {}
37
38void Options::NotifyOptionParsingStarting(ExecutionContext *execution_context) {
39 m_seen_options.clear();
40 // Let the subclass reset its option values
41 OptionParsingStarting(execution_context);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042}
43
Kate Stoneb9c1b512016-09-06 20:57:50 +000044Error Options::NotifyOptionParsingFinished(
45 ExecutionContext *execution_context) {
46 return OptionParsingFinished(execution_context);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047}
48
Kate Stoneb9c1b512016-09-06 20:57:50 +000049void Options::OptionSeen(int option_idx) { m_seen_options.insert(option_idx); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +000050
51// Returns true is set_a is a subset of set_b; Otherwise returns false.
52
Kate Stoneb9c1b512016-09-06 20:57:50 +000053bool Options::IsASubset(const OptionSet &set_a, const OptionSet &set_b) {
54 bool is_a_subset = true;
55 OptionSet::const_iterator pos_a;
56 OptionSet::const_iterator pos_b;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057
Kate Stoneb9c1b512016-09-06 20:57:50 +000058 // set_a is a subset of set_b if every member of set_a is also a member of
59 // set_b
Chris Lattner30fdc8d2010-06-08 16:52:24 +000060
Kate Stoneb9c1b512016-09-06 20:57:50 +000061 for (pos_a = set_a.begin(); pos_a != set_a.end() && is_a_subset; ++pos_a) {
62 pos_b = set_b.find(*pos_a);
63 if (pos_b == set_b.end())
64 is_a_subset = false;
65 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066
Kate Stoneb9c1b512016-09-06 20:57:50 +000067 return is_a_subset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000068}
69
Kate Stoneb9c1b512016-09-06 20:57:50 +000070// Returns the set difference set_a - set_b, i.e. { x | ElementOf (x, set_a) &&
71// !ElementOf (x, set_b) }
Chris Lattner30fdc8d2010-06-08 16:52:24 +000072
Kate Stoneb9c1b512016-09-06 20:57:50 +000073size_t Options::OptionsSetDiff(const OptionSet &set_a, const OptionSet &set_b,
74 OptionSet &diffs) {
75 size_t num_diffs = 0;
76 OptionSet::const_iterator pos_a;
77 OptionSet::const_iterator pos_b;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000078
Kate Stoneb9c1b512016-09-06 20:57:50 +000079 for (pos_a = set_a.begin(); pos_a != set_a.end(); ++pos_a) {
80 pos_b = set_b.find(*pos_a);
81 if (pos_b == set_b.end()) {
82 ++num_diffs;
83 diffs.insert(*pos_a);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000084 }
Kate Stoneb9c1b512016-09-06 20:57:50 +000085 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +000086
Kate Stoneb9c1b512016-09-06 20:57:50 +000087 return num_diffs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000088}
89
Kate Stoneb9c1b512016-09-06 20:57:50 +000090// Returns the union of set_a and set_b. Does not put duplicate members into
91// the union.
Chris Lattner30fdc8d2010-06-08 16:52:24 +000092
Kate Stoneb9c1b512016-09-06 20:57:50 +000093void Options::OptionsSetUnion(const OptionSet &set_a, const OptionSet &set_b,
94 OptionSet &union_set) {
95 OptionSet::const_iterator pos;
96 OptionSet::iterator pos_union;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000097
Kate Stoneb9c1b512016-09-06 20:57:50 +000098 // Put all the elements of set_a into the union.
Chris Lattner30fdc8d2010-06-08 16:52:24 +000099
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100 for (pos = set_a.begin(); pos != set_a.end(); ++pos)
101 union_set.insert(*pos);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103 // Put all the elements of set_b that are not already there into the union.
104 for (pos = set_b.begin(); pos != set_b.end(); ++pos) {
105 pos_union = union_set.find(*pos);
106 if (pos_union == union_set.end())
107 union_set.insert(*pos);
108 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000109}
110
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111bool Options::VerifyOptions(CommandReturnObject &result) {
112 bool options_are_valid = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000113
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114 int num_levels = GetRequiredOptions().size();
115 if (num_levels) {
116 for (int i = 0; i < num_levels && !options_are_valid; ++i) {
117 // This is the correct set of options if: 1). m_seen_options contains all
118 // of m_required_options[i]
119 // (i.e. all the required options at this level are a subset of
120 // m_seen_options); AND
121 // 2). { m_seen_options - m_required_options[i] is a subset of
122 // m_options_options[i] (i.e. all the rest of
123 // m_seen_options are in the set of optional options at this level.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125 // Check to see if all of m_required_options[i] are a subset of
126 // m_seen_options
127 if (IsASubset(GetRequiredOptions()[i], m_seen_options)) {
128 // Construct the set difference: remaining_options = {m_seen_options} -
129 // {m_required_options[i]}
130 OptionSet remaining_options;
131 OptionsSetDiff(m_seen_options, GetRequiredOptions()[i],
132 remaining_options);
133 // Check to see if remaining_options is a subset of
134 // m_optional_options[i]
135 if (IsASubset(remaining_options, GetOptionalOptions()[i]))
136 options_are_valid = true;
137 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000138 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 } else {
140 options_are_valid = true;
141 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000142
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 if (options_are_valid) {
144 result.SetStatus(eReturnStatusSuccessFinishNoResult);
145 } else {
146 result.AppendError("invalid combination of options for the given command");
147 result.SetStatus(eReturnStatusFailed);
148 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000149
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150 return options_are_valid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000151}
152
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153// This is called in the Options constructor, though we could call it lazily if
154// that ends up being
Jim Ingham86511212010-06-15 18:47:14 +0000155// a performance problem.
156
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157void Options::BuildValidOptionSets() {
158 // Check to see if we already did this.
159 if (m_required_options.size() != 0)
160 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000161
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 // Check to see if there are any options.
163 int num_options = NumCommandOptions();
164 if (num_options == 0)
165 return;
166
167 const OptionDefinition *opt_defs = GetDefinitions();
168 m_required_options.resize(1);
169 m_optional_options.resize(1);
170
171 // First count the number of option sets we've got. Ignore
172 // LLDB_ALL_OPTION_SETS...
173
174 uint32_t num_option_sets = 0;
175
176 for (int i = 0; i < num_options; i++) {
177 uint32_t this_usage_mask = opt_defs[i].usage_mask;
178 if (this_usage_mask == LLDB_OPT_SET_ALL) {
179 if (num_option_sets == 0)
180 num_option_sets = 1;
181 } else {
182 for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++) {
183 if (this_usage_mask & (1 << j)) {
184 if (num_option_sets <= j)
185 num_option_sets = j + 1;
186 }
187 }
188 }
189 }
190
191 if (num_option_sets > 0) {
192 m_required_options.resize(num_option_sets);
193 m_optional_options.resize(num_option_sets);
194
195 for (int i = 0; i < num_options; ++i) {
196 for (uint32_t j = 0; j < num_option_sets; j++) {
197 if (opt_defs[i].usage_mask & 1 << j) {
198 if (opt_defs[i].required)
199 m_required_options[j].insert(opt_defs[i].short_option);
200 else
201 m_optional_options[j].insert(opt_defs[i].short_option);
202 }
203 }
204 }
205 }
206}
207
208uint32_t Options::NumCommandOptions() {
209 const OptionDefinition *opt_defs = GetDefinitions();
210 if (opt_defs == nullptr)
211 return 0;
212
213 int i = 0;
214
215 if (opt_defs != nullptr) {
216 while (opt_defs[i].long_option != nullptr)
217 ++i;
218 }
219
220 return i;
221}
222
223Option *Options::GetLongOptions() {
224 // Check to see if this has already been done.
225 if (m_getopt_table.empty()) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000226 // Check to see if there are any options.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000227 const uint32_t num_options = NumCommandOptions();
Jim Ingham86511212010-06-15 18:47:14 +0000228 if (num_options == 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 return nullptr;
230
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000231 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232 const OptionDefinition *opt_defs = GetDefinitions();
Enrico Granata4ebb8a42016-03-15 01:17:32 +0000233
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234 std::map<int, uint32_t> option_seen;
Enrico Granata4ebb8a42016-03-15 01:17:32 +0000235
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236 m_getopt_table.resize(num_options + 1);
237 for (i = 0; i < num_options; ++i) {
238 const int short_opt = opt_defs[i].short_option;
Greg Claytoned8a7052010-09-18 03:37:20 +0000239
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240 m_getopt_table[i].definition = &opt_defs[i];
241 m_getopt_table[i].flag = nullptr;
242 m_getopt_table[i].val = short_opt;
Enrico Granatabef55ac2016-03-14 22:17:04 +0000243
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 if (option_seen.find(short_opt) == option_seen.end()) {
245 option_seen[short_opt] = i;
246 } else if (short_opt) {
247 m_getopt_table[i].val = 0;
248 std::map<int, uint32_t>::const_iterator pos =
249 option_seen.find(short_opt);
250 StreamString strm;
251 if (isprint8(short_opt))
252 Host::SystemLog(Host::eSystemLogError,
253 "option[%u] --%s has a short option -%c that "
254 "conflicts with option[%u] --%s, short option won't "
255 "be used for --%s\n",
256 i, opt_defs[i].long_option, short_opt, pos->second,
257 m_getopt_table[pos->second].definition->long_option,
258 opt_defs[i].long_option);
259 else
260 Host::SystemLog(Host::eSystemLogError,
261 "option[%u] --%s has a short option 0x%x that "
262 "conflicts with option[%u] --%s, short option won't "
263 "be used for --%s\n",
264 i, opt_defs[i].long_option, short_opt, pos->second,
265 m_getopt_table[pos->second].definition->long_option,
266 opt_defs[i].long_option);
267 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000268 }
269
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270 // getopt_long_only requires a NULL final entry in the table:
271
272 m_getopt_table[i].definition = nullptr;
273 m_getopt_table[i].flag = nullptr;
274 m_getopt_table[i].val = 0;
275 }
276
277 if (m_getopt_table.empty())
278 return nullptr;
279
280 return &m_getopt_table.front();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000281}
282
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283// This function takes INDENT, which tells how many spaces to output at the
284// front of each line; SPACES, which is
285// a string containing 80 spaces; and TEXT, which is the text that is to be
286// output. It outputs the text, on
287// multiple lines if necessary, to RESULT, with INDENT spaces at the front of
288// each line. It breaks lines on spaces,
289// tabs or newlines, shortening the line if necessary to not break in the middle
290// of a word. It assumes that each
291// output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000292
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293void Options::OutputFormattedUsageText(Stream &strm,
294 const OptionDefinition &option_def,
295 uint32_t output_max_columns) {
296 std::string actual_text;
297 if (option_def.validator) {
298 const char *condition = option_def.validator->ShortConditionString();
299 if (condition) {
300 actual_text = "[";
301 actual_text.append(condition);
302 actual_text.append("] ");
303 }
304 }
305 actual_text.append(option_def.usage_text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000306
Kate Stoneb9c1b512016-09-06 20:57:50 +0000307 // Will it all fit on one line?
308
309 if (static_cast<uint32_t>(actual_text.length() + strm.GetIndentLevel()) <
310 output_max_columns) {
311 // Output it as a single line.
312 strm.Indent(actual_text.c_str());
313 strm.EOL();
314 } else {
315 // We need to break it up into multiple lines.
316
317 int text_width = output_max_columns - strm.GetIndentLevel() - 1;
318 int start = 0;
319 int end = start;
320 int final_end = actual_text.length();
321 int sub_len;
322
323 while (end < final_end) {
324 // Don't start the 'text' on a space, since we're already outputting the
325 // indentation.
326 while ((start < final_end) && (actual_text[start] == ' '))
327 start++;
328
329 end = start + text_width;
330 if (end > final_end)
331 end = final_end;
332 else {
333 // If we're not at the end of the text, make sure we break the line on
334 // white space.
335 while (end > start && actual_text[end] != ' ' &&
336 actual_text[end] != '\t' && actual_text[end] != '\n')
337 end--;
338 }
339
340 sub_len = end - start;
341 if (start != 0)
342 strm.EOL();
343 strm.Indent();
344 assert(start < final_end);
345 assert(start + sub_len <= final_end);
346 strm.Write(actual_text.c_str() + start, sub_len);
347 start = end + 1;
348 }
349 strm.EOL();
350 }
351}
352
353bool Options::SupportsLongOption(const char *long_option) {
354 if (long_option && long_option[0]) {
355 const OptionDefinition *opt_defs = GetDefinitions();
356 if (opt_defs) {
357 const char *long_option_name = long_option;
358 if (long_option[0] == '-' && long_option[1] == '-')
359 long_option_name += 2;
360
361 for (uint32_t i = 0; opt_defs[i].long_option; ++i) {
362 if (strcmp(opt_defs[i].long_option, long_option_name) == 0)
363 return true;
364 }
365 }
366 }
367 return false;
368}
369
370enum OptionDisplayType {
371 eDisplayBestOption,
372 eDisplayShortOption,
373 eDisplayLongOption
374};
375
376static bool PrintOption(const OptionDefinition &opt_def,
377 OptionDisplayType display_type, const char *header,
378 const char *footer, bool show_optional, Stream &strm) {
379 const bool has_short_option = isprint8(opt_def.short_option) != 0;
380
381 if (display_type == eDisplayShortOption && !has_short_option)
382 return false;
383
384 if (header && header[0])
385 strm.PutCString(header);
386
387 if (show_optional && !opt_def.required)
388 strm.PutChar('[');
389 const bool show_short_option =
390 has_short_option && display_type != eDisplayLongOption;
391 if (show_short_option)
392 strm.Printf("-%c", opt_def.short_option);
393 else
394 strm.Printf("--%s", opt_def.long_option);
395 switch (opt_def.option_has_arg) {
396 case OptionParser::eNoArgument:
397 break;
398 case OptionParser::eRequiredArgument:
399 strm.Printf(" <%s>", CommandObject::GetArgumentName(opt_def.argument_type));
400 break;
401
402 case OptionParser::eOptionalArgument:
403 strm.Printf("%s[<%s>]", show_short_option ? "" : "=",
404 CommandObject::GetArgumentName(opt_def.argument_type));
405 break;
406 }
407 if (show_optional && !opt_def.required)
408 strm.PutChar(']');
409 if (footer && footer[0])
410 strm.PutCString(footer);
411 return true;
412}
413
414void Options::GenerateOptionUsage(Stream &strm, CommandObject *cmd,
415 uint32_t screen_width) {
416 const bool only_print_args = cmd->IsDashDashCommand();
417
418 const OptionDefinition *opt_defs = GetDefinitions();
419 const uint32_t save_indent_level = strm.GetIndentLevel();
420 const char *name;
421
422 StreamString arguments_str;
423
424 if (cmd) {
425 name = cmd->GetCommandName();
426 cmd->GetFormattedCommandArguments(arguments_str);
427 } else
428 name = "";
429
430 strm.PutCString("\nCommand Options Usage:\n");
431
432 strm.IndentMore(2);
433
434 // First, show each usage level set of options, e.g. <cmd>
435 // [options-for-level-0]
436 // <cmd>
437 // [options-for-level-1]
438 // etc.
439
440 const uint32_t num_options = NumCommandOptions();
441 if (num_options == 0)
442 return;
443
444 uint32_t num_option_sets = GetRequiredOptions().size();
445
446 uint32_t i;
447
448 if (!only_print_args) {
449 for (uint32_t opt_set = 0; opt_set < num_option_sets; ++opt_set) {
450 uint32_t opt_set_mask;
451
452 opt_set_mask = 1 << opt_set;
453 if (opt_set > 0)
454 strm.Printf("\n");
455 strm.Indent(name);
456
457 // Different option sets may require different args.
458 StreamString args_str;
459 if (cmd)
460 cmd->GetFormattedCommandArguments(args_str, opt_set_mask);
461
462 // First go through and print all options that take no arguments as
463 // a single string. If a command has "-a" "-b" and "-c", this will show
464 // up as [-abc]
465
466 std::set<int> options;
467 std::set<int>::const_iterator options_pos, options_end;
468 for (i = 0; i < num_options; ++i) {
469 if (opt_defs[i].usage_mask & opt_set_mask &&
470 isprint8(opt_defs[i].short_option)) {
471 // Add current option to the end of out_stream.
472
473 if (opt_defs[i].required == true &&
474 opt_defs[i].option_has_arg == OptionParser::eNoArgument) {
475 options.insert(opt_defs[i].short_option);
476 }
477 }
478 }
479
480 if (options.empty() == false) {
481 // We have some required options with no arguments
482 strm.PutCString(" -");
483 for (i = 0; i < 2; ++i)
484 for (options_pos = options.begin(), options_end = options.end();
485 options_pos != options_end; ++options_pos) {
486 if (i == 0 && ::islower(*options_pos))
487 continue;
488 if (i == 1 && ::isupper(*options_pos))
489 continue;
490 strm << (char)*options_pos;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000491 }
492 }
493
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 for (i = 0, options.clear(); i < num_options; ++i) {
495 if (opt_defs[i].usage_mask & opt_set_mask &&
496 isprint8(opt_defs[i].short_option)) {
497 // Add current option to the end of out_stream.
498
499 if (opt_defs[i].required == false &&
500 opt_defs[i].option_has_arg == OptionParser::eNoArgument) {
501 options.insert(opt_defs[i].short_option);
502 }
503 }
504 }
505
506 if (options.empty() == false) {
507 // We have some required options with no arguments
508 strm.PutCString(" [-");
509 for (i = 0; i < 2; ++i)
510 for (options_pos = options.begin(), options_end = options.end();
511 options_pos != options_end; ++options_pos) {
512 if (i == 0 && ::islower(*options_pos))
513 continue;
514 if (i == 1 && ::isupper(*options_pos))
515 continue;
516 strm << (char)*options_pos;
517 }
518 strm.PutChar(']');
519 }
520
521 // First go through and print the required options (list them up front).
522
523 for (i = 0; i < num_options; ++i) {
524 if (opt_defs[i].usage_mask & opt_set_mask &&
525 isprint8(opt_defs[i].short_option)) {
526 if (opt_defs[i].required &&
527 opt_defs[i].option_has_arg != OptionParser::eNoArgument)
528 PrintOption(opt_defs[i], eDisplayBestOption, " ", nullptr, true,
529 strm);
530 }
531 }
532
533 // Now go through again, and this time only print the optional options.
534
535 for (i = 0; i < num_options; ++i) {
536 if (opt_defs[i].usage_mask & opt_set_mask) {
537 // Add current option to the end of out_stream.
538
539 if (!opt_defs[i].required &&
540 opt_defs[i].option_has_arg != OptionParser::eNoArgument)
541 PrintOption(opt_defs[i], eDisplayBestOption, " ", nullptr, true,
542 strm);
543 }
544 }
545
546 if (args_str.GetSize() > 0) {
547 if (cmd->WantsRawCommandString() && !only_print_args)
548 strm.Printf(" --");
549
550 strm.Printf(" %s", args_str.GetData());
551 if (only_print_args)
552 break;
553 }
554 }
555 }
556
557 if (cmd && (only_print_args || cmd->WantsRawCommandString()) &&
558 arguments_str.GetSize() > 0) {
559 if (!only_print_args)
560 strm.PutChar('\n');
561 strm.Indent(name);
562 strm.Printf(" %s", arguments_str.GetData());
563 }
564
565 strm.Printf("\n\n");
566
567 if (!only_print_args) {
568 // Now print out all the detailed information about the various options:
569 // long form, short form and help text:
570 // -short <argument> ( --long_name <argument> )
571 // help text
572
573 // This variable is used to keep track of which options' info we've printed
574 // out, because some options can be in
575 // more than one usage level, but we only want to print the long form of its
576 // information once.
577
578 std::multimap<int, uint32_t> options_seen;
579 strm.IndentMore(5);
580
581 // Put the unique command options in a vector & sort it, so we can output
582 // them alphabetically (by short_option)
583 // when writing out detailed help for each option.
584
585 for (i = 0; i < num_options; ++i)
586 options_seen.insert(std::make_pair(opt_defs[i].short_option, i));
587
588 // Go through the unique'd and alphabetically sorted vector of options, find
589 // the table entry for each option
590 // and write out the detailed help information for that option.
591
592 bool first_option_printed = false;
593 ;
594
595 for (auto pos : options_seen) {
596 i = pos.second;
597 // Print out the help information for this option.
598
599 // Put a newline separation between arguments
600 if (first_option_printed)
601 strm.EOL();
602 else
603 first_option_printed = true;
604
605 CommandArgumentType arg_type = opt_defs[i].argument_type;
606
607 StreamString arg_name_str;
608 arg_name_str.Printf("<%s>", CommandObject::GetArgumentName(arg_type));
609
610 strm.Indent();
611 if (opt_defs[i].short_option && isprint8(opt_defs[i].short_option)) {
612 PrintOption(opt_defs[i], eDisplayShortOption, nullptr, nullptr, false,
613 strm);
614 PrintOption(opt_defs[i], eDisplayLongOption, " ( ", " )", false, strm);
615 } else {
616 // Short option is not printable, just print long option
617 PrintOption(opt_defs[i], eDisplayLongOption, nullptr, nullptr, false,
618 strm);
619 }
620 strm.EOL();
621
622 strm.IndentMore(5);
623
624 if (opt_defs[i].usage_text)
625 OutputFormattedUsageText(strm, opt_defs[i], screen_width);
626 if (opt_defs[i].enum_values != nullptr) {
627 strm.Indent();
628 strm.Printf("Values: ");
629 for (int k = 0; opt_defs[i].enum_values[k].string_value != nullptr;
630 k++) {
631 if (k == 0)
632 strm.Printf("%s", opt_defs[i].enum_values[k].string_value);
633 else
634 strm.Printf(" | %s", opt_defs[i].enum_values[k].string_value);
635 }
636 strm.EOL();
637 }
638 strm.IndentLess(5);
639 }
640 }
641
642 // Restore the indent level
643 strm.SetIndentLevel(save_indent_level);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000644}
645
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646// This function is called when we have been given a potentially incomplete set
647// of
648// options, such as when an alias has been defined (more options might be added
649// at
650// at the time the alias is invoked). We need to verify that the options in the
651// set
652// m_seen_options are all part of a set that may be used together, but
653// m_seen_options
654// may be missing some of the "required" options.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000655
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656bool Options::VerifyPartialOptions(CommandReturnObject &result) {
657 bool options_are_valid = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000658
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 int num_levels = GetRequiredOptions().size();
660 if (num_levels) {
661 for (int i = 0; i < num_levels && !options_are_valid; ++i) {
662 // In this case we are treating all options as optional rather than
663 // required.
664 // Therefore a set of options is correct if m_seen_options is a subset of
665 // the
666 // union of m_required_options and m_optional_options.
667 OptionSet union_set;
668 OptionsSetUnion(GetRequiredOptions()[i], GetOptionalOptions()[i],
669 union_set);
670 if (IsASubset(m_seen_options, union_set))
671 options_are_valid = true;
672 }
673 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000674
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 return options_are_valid;
676}
Jim Inghamd6ccc602010-06-24 20:30:15 +0000677
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678bool Options::HandleOptionCompletion(
679 Args &input, OptionElementVector &opt_element_vector, int cursor_index,
680 int char_pos, int match_start_point, int max_return_elements,
681 CommandInterpreter &interpreter, bool &word_complete,
682 lldb_private::StringList &matches) {
683 word_complete = true;
684
685 // For now we just scan the completions to see if the cursor position is in
686 // an option or its argument. Otherwise we'll call HandleArgumentCompletion.
687 // In the future we can use completion to validate options as well if we want.
688
689 const OptionDefinition *opt_defs = GetDefinitions();
690
691 std::string cur_opt_std_str(input.GetArgumentAtIndex(cursor_index));
692 cur_opt_std_str.erase(char_pos);
693 const char *cur_opt_str = cur_opt_std_str.c_str();
694
695 for (size_t i = 0; i < opt_element_vector.size(); i++) {
696 int opt_pos = opt_element_vector[i].opt_pos;
697 int opt_arg_pos = opt_element_vector[i].opt_arg_pos;
698 int opt_defs_index = opt_element_vector[i].opt_defs_index;
699 if (opt_pos == cursor_index) {
700 // We're completing the option itself.
701
702 if (opt_defs_index == OptionArgElement::eBareDash) {
703 // We're completing a bare dash. That means all options are open.
704 // FIXME: We should scan the other options provided and only complete
705 // options
706 // within the option group they belong to.
707 char opt_str[3] = {'-', 'a', '\0'};
708
709 for (int j = 0; opt_defs[j].short_option != 0; j++) {
710 opt_str[1] = opt_defs[j].short_option;
711 matches.AppendString(opt_str);
712 }
713 return true;
714 } else if (opt_defs_index == OptionArgElement::eBareDoubleDash) {
715 std::string full_name("--");
716 for (int j = 0; opt_defs[j].short_option != 0; j++) {
717 full_name.erase(full_name.begin() + 2, full_name.end());
718 full_name.append(opt_defs[j].long_option);
719 matches.AppendString(full_name.c_str());
720 }
721 return true;
722 } else if (opt_defs_index != OptionArgElement::eUnrecognizedArg) {
723 // We recognized it, if it an incomplete long option, complete it anyway
724 // (getopt_long_only is
725 // happy with shortest unique string, but it's still a nice thing to
726 // do.) Otherwise return
727 // The string so the upper level code will know this is a full match and
728 // add the " ".
729 if (cur_opt_str && strlen(cur_opt_str) > 2 && cur_opt_str[0] == '-' &&
730 cur_opt_str[1] == '-' &&
731 strcmp(opt_defs[opt_defs_index].long_option, cur_opt_str) != 0) {
732 std::string full_name("--");
733 full_name.append(opt_defs[opt_defs_index].long_option);
734 matches.AppendString(full_name.c_str());
735 return true;
736 } else {
737 matches.AppendString(input.GetArgumentAtIndex(cursor_index));
738 return true;
739 }
740 } else {
741 // FIXME - not handling wrong options yet:
742 // Check to see if they are writing a long option & complete it.
743 // I think we will only get in here if the long option table has two
744 // elements
745 // that are not unique up to this point. getopt_long_only does shortest
746 // unique match
747 // for long options already.
748
749 if (cur_opt_str && strlen(cur_opt_str) > 2 && cur_opt_str[0] == '-' &&
750 cur_opt_str[1] == '-') {
751 for (int j = 0; opt_defs[j].short_option != 0; j++) {
752 if (strstr(opt_defs[j].long_option, cur_opt_str + 2) ==
753 opt_defs[j].long_option) {
754 std::string full_name("--");
755 full_name.append(opt_defs[j].long_option);
756 // The options definitions table has duplicates because of the
757 // way the grouping information is stored, so only add once.
758 bool duplicate = false;
759 for (size_t k = 0; k < matches.GetSize(); k++) {
760 if (matches.GetStringAtIndex(k) == full_name) {
761 duplicate = true;
762 break;
Jim Inghamd6ccc602010-06-24 20:30:15 +0000763 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764 }
765 if (!duplicate)
766 matches.AppendString(full_name.c_str());
Jim Inghamd6ccc602010-06-24 20:30:15 +0000767 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000769 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000770 return true;
771 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000772
Kate Stoneb9c1b512016-09-06 20:57:50 +0000773 } else if (opt_arg_pos == cursor_index) {
774 // Okay the cursor is on the completion of an argument.
775 // See if it has a completion, otherwise return no matches.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000776
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777 if (opt_defs_index != -1) {
778 HandleOptionArgumentCompletion(
779 input, cursor_index, strlen(input.GetArgumentAtIndex(cursor_index)),
780 opt_element_vector, i, match_start_point, max_return_elements,
781 interpreter, word_complete, matches);
782 return true;
783 } else {
784 // No completion callback means no completions...
785 return true;
786 }
787
788 } else {
789 // Not the last element, keep going.
790 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000791 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000792 }
793 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000794}
795
Kate Stoneb9c1b512016-09-06 20:57:50 +0000796bool Options::HandleOptionArgumentCompletion(
797 Args &input, int cursor_index, int char_pos,
798 OptionElementVector &opt_element_vector, int opt_element_index,
799 int match_start_point, int max_return_elements,
800 CommandInterpreter &interpreter, bool &word_complete,
801 lldb_private::StringList &matches) {
802 const OptionDefinition *opt_defs = GetDefinitions();
803 std::unique_ptr<SearchFilter> filter_ap;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000804
Kate Stoneb9c1b512016-09-06 20:57:50 +0000805 int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos;
806 int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
807
808 // See if this is an enumeration type option, and if so complete it here:
809
810 OptionEnumValueElement *enum_values = opt_defs[opt_defs_index].enum_values;
811 if (enum_values != nullptr) {
812 bool return_value = false;
813 std::string match_string(input.GetArgumentAtIndex(opt_arg_pos),
814 input.GetArgumentAtIndex(opt_arg_pos) + char_pos);
815 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
816 if (strstr(enum_values[i].string_value, match_string.c_str()) ==
817 enum_values[i].string_value) {
818 matches.AppendString(enum_values[i].string_value);
819 return_value = true;
820 }
821 }
822 return return_value;
823 }
824
825 // If this is a source file or symbol type completion, and there is a
826 // -shlib option somewhere in the supplied arguments, then make a search
827 // filter
828 // for that shared library.
829 // FIXME: Do we want to also have an "OptionType" so we don't have to match
830 // string names?
831
832 uint32_t completion_mask = opt_defs[opt_defs_index].completion_type;
833
834 if (completion_mask == 0) {
835 lldb::CommandArgumentType option_arg_type =
836 opt_defs[opt_defs_index].argument_type;
837 if (option_arg_type != eArgTypeNone) {
838 const CommandObject::ArgumentTableEntry *arg_entry =
839 CommandObject::FindArgumentDataByType(
840 opt_defs[opt_defs_index].argument_type);
841 if (arg_entry)
842 completion_mask = arg_entry->completion_type;
843 }
844 }
845
846 if (completion_mask & CommandCompletions::eSourceFileCompletion ||
847 completion_mask & CommandCompletions::eSymbolCompletion) {
848 for (size_t i = 0; i < opt_element_vector.size(); i++) {
849 int cur_defs_index = opt_element_vector[i].opt_defs_index;
850
851 // trying to use <0 indices will definitely cause problems
852 if (cur_defs_index == OptionArgElement::eUnrecognizedArg ||
853 cur_defs_index == OptionArgElement::eBareDash ||
854 cur_defs_index == OptionArgElement::eBareDoubleDash)
855 continue;
856
857 int cur_arg_pos = opt_element_vector[i].opt_arg_pos;
858 const char *cur_opt_name = opt_defs[cur_defs_index].long_option;
859
860 // If this is the "shlib" option and there was an argument provided,
861 // restrict it to that shared library.
862 if (cur_opt_name && strcmp(cur_opt_name, "shlib") == 0 &&
863 cur_arg_pos != -1) {
864 const char *module_name = input.GetArgumentAtIndex(cur_arg_pos);
865 if (module_name) {
866 FileSpec module_spec(module_name, false);
867 lldb::TargetSP target_sp =
868 interpreter.GetDebugger().GetSelectedTarget();
869 // Search filters require a target...
870 if (target_sp)
871 filter_ap.reset(new SearchFilterByModule(target_sp, module_spec));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000872 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873 break;
874 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000875 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000876 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000877
Kate Stoneb9c1b512016-09-06 20:57:50 +0000878 return CommandCompletions::InvokeCommonCompletionCallbacks(
879 interpreter, completion_mask, input.GetArgumentAtIndex(opt_arg_pos),
880 match_start_point, max_return_elements, filter_ap.get(), word_complete,
881 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000882}
Greg Claytonf6b8b582011-04-13 00:18:08 +0000883
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884void OptionGroupOptions::Append(OptionGroup *group) {
885 const OptionDefinition *group_option_defs = group->GetDefinitions();
886 const uint32_t group_option_count = group->GetNumDefinitions();
887 for (uint32_t i = 0; i < group_option_count; ++i) {
888 m_option_infos.push_back(OptionInfo(group, i));
889 m_option_defs.push_back(group_option_defs[i]);
890 }
Greg Clayton84c39662011-04-27 22:04:39 +0000891}
892
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893const OptionGroup *OptionGroupOptions::GetGroupWithOption(char short_opt) {
894 for (uint32_t i = 0; i < m_option_defs.size(); i++) {
895 OptionDefinition opt_def = m_option_defs[i];
896 if (opt_def.short_option == short_opt)
897 return m_option_infos[i].option_group;
898 }
899 return nullptr;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000900}
901
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902void OptionGroupOptions::Append(OptionGroup *group, uint32_t src_mask,
903 uint32_t dst_mask) {
904 const OptionDefinition *group_option_defs = group->GetDefinitions();
905 const uint32_t group_option_count = group->GetNumDefinitions();
906 for (uint32_t i = 0; i < group_option_count; ++i) {
907 if (group_option_defs[i].usage_mask & src_mask) {
908 m_option_infos.push_back(OptionInfo(group, i));
909 m_option_defs.push_back(group_option_defs[i]);
910 m_option_defs.back().usage_mask = dst_mask;
Greg Claytonf6b8b582011-04-13 00:18:08 +0000911 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 }
Greg Claytonf6b8b582011-04-13 00:18:08 +0000913}
914
Kate Stoneb9c1b512016-09-06 20:57:50 +0000915void OptionGroupOptions::Finalize() {
916 m_did_finalize = true;
917 OptionDefinition empty_option_def = {
918 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr};
919 m_option_defs.push_back(empty_option_def);
Greg Claytonf6b8b582011-04-13 00:18:08 +0000920}
921
Kate Stoneb9c1b512016-09-06 20:57:50 +0000922Error OptionGroupOptions::SetOptionValue(uint32_t option_idx,
923 const char *option_value,
924 ExecutionContext *execution_context) {
925 // After calling OptionGroupOptions::Append(...), you must finalize the groups
926 // by calling OptionGroupOptions::Finlize()
927 assert(m_did_finalize);
928 assert(m_option_infos.size() + 1 == m_option_defs.size());
929 Error error;
930 if (option_idx < m_option_infos.size()) {
931 error = m_option_infos[option_idx].option_group->SetOptionValue(
932 m_option_infos[option_idx].option_index, option_value,
933 execution_context);
934
935 } else {
936 error.SetErrorString("invalid option index"); // Shouldn't happen...
937 }
938 return error;
Greg Claytonf6b8b582011-04-13 00:18:08 +0000939}
940
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941void OptionGroupOptions::OptionParsingStarting(
942 ExecutionContext *execution_context) {
943 std::set<OptionGroup *> group_set;
944 OptionInfos::iterator pos, end = m_option_infos.end();
945 for (pos = m_option_infos.begin(); pos != end; ++pos) {
946 OptionGroup *group = pos->option_group;
947 if (group_set.find(group) == group_set.end()) {
948 group->OptionParsingStarting(execution_context);
949 group_set.insert(group);
Greg Claytonab65b342011-04-13 22:47:15 +0000950 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951 }
Greg Claytonf6b8b582011-04-13 00:18:08 +0000952}
Kate Stoneb9c1b512016-09-06 20:57:50 +0000953Error OptionGroupOptions::OptionParsingFinished(
954 ExecutionContext *execution_context) {
955 std::set<OptionGroup *> group_set;
956 Error error;
957 OptionInfos::iterator pos, end = m_option_infos.end();
958 for (pos = m_option_infos.begin(); pos != end; ++pos) {
959 OptionGroup *group = pos->option_group;
960 if (group_set.find(group) == group_set.end()) {
961 error = group->OptionParsingFinished(execution_context);
962 group_set.insert(group);
963 if (error.Fail())
964 return error;
Greg Claytonf6b8b582011-04-13 00:18:08 +0000965 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966 }
967 return error;
Greg Claytonf6b8b582011-04-13 00:18:08 +0000968}