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