File: | build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/lldb/source/Interpreter/Options.cpp |
Warning: | line 934, column 19 Forming reference to null pointer |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===-- Options.cpp -------------------------------------------------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | ||||
9 | #include "lldb/Interpreter/Options.h" | |||
10 | ||||
11 | #include <algorithm> | |||
12 | #include <bitset> | |||
13 | #include <map> | |||
14 | #include <set> | |||
15 | ||||
16 | #include "lldb/Host/OptionParser.h" | |||
17 | #include "lldb/Interpreter/CommandCompletions.h" | |||
18 | #include "lldb/Interpreter/CommandInterpreter.h" | |||
19 | #include "lldb/Interpreter/CommandObject.h" | |||
20 | #include "lldb/Interpreter/CommandReturnObject.h" | |||
21 | #include "lldb/Target/Target.h" | |||
22 | #include "lldb/Utility/StreamString.h" | |||
23 | ||||
24 | using namespace lldb; | |||
25 | using namespace lldb_private; | |||
26 | ||||
27 | // Options | |||
28 | Options::Options() { BuildValidOptionSets(); } | |||
29 | ||||
30 | Options::~Options() = default; | |||
31 | ||||
32 | void Options::NotifyOptionParsingStarting(ExecutionContext *execution_context) { | |||
33 | m_seen_options.clear(); | |||
34 | // Let the subclass reset its option values | |||
35 | OptionParsingStarting(execution_context); | |||
36 | } | |||
37 | ||||
38 | Status | |||
39 | Options::NotifyOptionParsingFinished(ExecutionContext *execution_context) { | |||
40 | return OptionParsingFinished(execution_context); | |||
41 | } | |||
42 | ||||
43 | void Options::OptionSeen(int option_idx) { m_seen_options.insert(option_idx); } | |||
44 | ||||
45 | // Returns true is set_a is a subset of set_b; Otherwise returns false. | |||
46 | ||||
47 | bool Options::IsASubset(const OptionSet &set_a, const OptionSet &set_b) { | |||
48 | bool is_a_subset = true; | |||
49 | OptionSet::const_iterator pos_a; | |||
50 | OptionSet::const_iterator pos_b; | |||
51 | ||||
52 | // set_a is a subset of set_b if every member of set_a is also a member of | |||
53 | // set_b | |||
54 | ||||
55 | for (pos_a = set_a.begin(); pos_a != set_a.end() && is_a_subset; ++pos_a) { | |||
56 | pos_b = set_b.find(*pos_a); | |||
57 | if (pos_b == set_b.end()) | |||
58 | is_a_subset = false; | |||
59 | } | |||
60 | ||||
61 | return is_a_subset; | |||
62 | } | |||
63 | ||||
64 | // Returns the set difference set_a - set_b, i.e. { x | ElementOf (x, set_a) && | |||
65 | // !ElementOf (x, set_b) } | |||
66 | ||||
67 | size_t Options::OptionsSetDiff(const OptionSet &set_a, const OptionSet &set_b, | |||
68 | OptionSet &diffs) { | |||
69 | size_t num_diffs = 0; | |||
70 | OptionSet::const_iterator pos_a; | |||
71 | OptionSet::const_iterator pos_b; | |||
72 | ||||
73 | for (pos_a = set_a.begin(); pos_a != set_a.end(); ++pos_a) { | |||
74 | pos_b = set_b.find(*pos_a); | |||
75 | if (pos_b == set_b.end()) { | |||
76 | ++num_diffs; | |||
77 | diffs.insert(*pos_a); | |||
78 | } | |||
79 | } | |||
80 | ||||
81 | return num_diffs; | |||
82 | } | |||
83 | ||||
84 | // Returns the union of set_a and set_b. Does not put duplicate members into | |||
85 | // the union. | |||
86 | ||||
87 | void Options::OptionsSetUnion(const OptionSet &set_a, const OptionSet &set_b, | |||
88 | OptionSet &union_set) { | |||
89 | OptionSet::const_iterator pos; | |||
90 | OptionSet::iterator pos_union; | |||
91 | ||||
92 | // Put all the elements of set_a into the union. | |||
93 | ||||
94 | for (pos = set_a.begin(); pos != set_a.end(); ++pos) | |||
95 | union_set.insert(*pos); | |||
96 | ||||
97 | // Put all the elements of set_b that are not already there into the union. | |||
98 | for (pos = set_b.begin(); pos != set_b.end(); ++pos) { | |||
99 | pos_union = union_set.find(*pos); | |||
100 | if (pos_union == union_set.end()) | |||
101 | union_set.insert(*pos); | |||
102 | } | |||
103 | } | |||
104 | ||||
105 | bool Options::VerifyOptions(CommandReturnObject &result) { | |||
106 | bool options_are_valid = false; | |||
107 | ||||
108 | int num_levels = GetRequiredOptions().size(); | |||
109 | if (num_levels) { | |||
110 | for (int i = 0; i < num_levels && !options_are_valid; ++i) { | |||
111 | // This is the correct set of options if: 1). m_seen_options contains | |||
112 | // all of m_required_options[i] (i.e. all the required options at this | |||
113 | // level are a subset of m_seen_options); AND 2). { m_seen_options - | |||
114 | // m_required_options[i] is a subset of m_options_options[i] (i.e. all | |||
115 | // the rest of m_seen_options are in the set of optional options at this | |||
116 | // level. | |||
117 | ||||
118 | // Check to see if all of m_required_options[i] are a subset of | |||
119 | // m_seen_options | |||
120 | if (IsASubset(GetRequiredOptions()[i], m_seen_options)) { | |||
121 | // Construct the set difference: remaining_options = {m_seen_options} - | |||
122 | // {m_required_options[i]} | |||
123 | OptionSet remaining_options; | |||
124 | OptionsSetDiff(m_seen_options, GetRequiredOptions()[i], | |||
125 | remaining_options); | |||
126 | // Check to see if remaining_options is a subset of | |||
127 | // m_optional_options[i] | |||
128 | if (IsASubset(remaining_options, GetOptionalOptions()[i])) | |||
129 | options_are_valid = true; | |||
130 | } | |||
131 | } | |||
132 | } else { | |||
133 | options_are_valid = true; | |||
134 | } | |||
135 | ||||
136 | if (options_are_valid) { | |||
137 | result.SetStatus(eReturnStatusSuccessFinishNoResult); | |||
138 | } else { | |||
139 | result.AppendError("invalid combination of options for the given command"); | |||
140 | } | |||
141 | ||||
142 | return options_are_valid; | |||
143 | } | |||
144 | ||||
145 | // This is called in the Options constructor, though we could call it lazily if | |||
146 | // that ends up being a performance problem. | |||
147 | ||||
148 | void Options::BuildValidOptionSets() { | |||
149 | // Check to see if we already did this. | |||
150 | if (m_required_options.size() != 0) | |||
151 | return; | |||
152 | ||||
153 | // Check to see if there are any options. | |||
154 | int num_options = NumCommandOptions(); | |||
155 | if (num_options == 0) | |||
156 | return; | |||
157 | ||||
158 | auto opt_defs = GetDefinitions(); | |||
159 | m_required_options.resize(1); | |||
160 | m_optional_options.resize(1); | |||
161 | ||||
162 | // First count the number of option sets we've got. Ignore | |||
163 | // LLDB_ALL_OPTION_SETS... | |||
164 | ||||
165 | uint32_t num_option_sets = 0; | |||
166 | ||||
167 | for (const auto &def : opt_defs) { | |||
168 | uint32_t this_usage_mask = def.usage_mask; | |||
169 | if (this_usage_mask == LLDB_OPT_SET_ALL0xFFFFFFFFU) { | |||
170 | if (num_option_sets == 0) | |||
171 | num_option_sets = 1; | |||
172 | } else { | |||
173 | for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS32; j++) { | |||
174 | if (this_usage_mask & (1 << j)) { | |||
175 | if (num_option_sets <= j) | |||
176 | num_option_sets = j + 1; | |||
177 | } | |||
178 | } | |||
179 | } | |||
180 | } | |||
181 | ||||
182 | if (num_option_sets > 0) { | |||
183 | m_required_options.resize(num_option_sets); | |||
184 | m_optional_options.resize(num_option_sets); | |||
185 | ||||
186 | for (const auto &def : opt_defs) { | |||
187 | for (uint32_t j = 0; j < num_option_sets; j++) { | |||
188 | if (def.usage_mask & 1 << j) { | |||
189 | if (def.required) | |||
190 | m_required_options[j].insert(def.short_option); | |||
191 | else | |||
192 | m_optional_options[j].insert(def.short_option); | |||
193 | } | |||
194 | } | |||
195 | } | |||
196 | } | |||
197 | } | |||
198 | ||||
199 | uint32_t Options::NumCommandOptions() { return GetDefinitions().size(); } | |||
200 | ||||
201 | Option *Options::GetLongOptions() { | |||
202 | // Check to see if this has already been done. | |||
203 | if (m_getopt_table.empty()) { | |||
204 | auto defs = GetDefinitions(); | |||
205 | if (defs.empty()) | |||
206 | return nullptr; | |||
207 | ||||
208 | std::map<int, uint32_t> option_seen; | |||
209 | ||||
210 | m_getopt_table.resize(defs.size() + 1); | |||
211 | for (size_t i = 0; i < defs.size(); ++i) { | |||
212 | const int short_opt = defs[i].short_option; | |||
213 | ||||
214 | m_getopt_table[i].definition = &defs[i]; | |||
215 | m_getopt_table[i].flag = nullptr; | |||
216 | m_getopt_table[i].val = short_opt; | |||
217 | ||||
218 | if (option_seen.find(short_opt) == option_seen.end()) { | |||
219 | option_seen[short_opt] = i; | |||
220 | } else if (short_opt) { | |||
221 | m_getopt_table[i].val = 0; | |||
222 | std::map<int, uint32_t>::const_iterator pos = | |||
223 | option_seen.find(short_opt); | |||
224 | StreamString strm; | |||
225 | if (defs[i].HasShortOption()) | |||
226 | Host::SystemLog(Host::eSystemLogError, | |||
227 | "option[%u] --%s has a short option -%c that " | |||
228 | "conflicts with option[%u] --%s, short option won't " | |||
229 | "be used for --%s\n", | |||
230 | (int)i, defs[i].long_option, short_opt, pos->second, | |||
231 | m_getopt_table[pos->second].definition->long_option, | |||
232 | defs[i].long_option); | |||
233 | else | |||
234 | Host::SystemLog(Host::eSystemLogError, | |||
235 | "option[%u] --%s has a short option 0x%x that " | |||
236 | "conflicts with option[%u] --%s, short option won't " | |||
237 | "be used for --%s\n", | |||
238 | (int)i, defs[i].long_option, short_opt, pos->second, | |||
239 | m_getopt_table[pos->second].definition->long_option, | |||
240 | defs[i].long_option); | |||
241 | } | |||
242 | } | |||
243 | ||||
244 | // getopt_long_only requires a NULL final entry in the table: | |||
245 | ||||
246 | m_getopt_table.back().definition = nullptr; | |||
247 | m_getopt_table.back().flag = nullptr; | |||
248 | m_getopt_table.back().val = 0; | |||
249 | } | |||
250 | ||||
251 | if (m_getopt_table.empty()) | |||
252 | return nullptr; | |||
253 | ||||
254 | return &m_getopt_table.front(); | |||
255 | } | |||
256 | ||||
257 | // This function takes INDENT, which tells how many spaces to output at the | |||
258 | // front of each line; SPACES, which is a string containing 80 spaces; and | |||
259 | // TEXT, which is the text that is to be output. It outputs the text, on | |||
260 | // multiple lines if necessary, to RESULT, with INDENT spaces at the front of | |||
261 | // each line. It breaks lines on spaces, tabs or newlines, shortening the line | |||
262 | // if necessary to not break in the middle of a word. It assumes that each | |||
263 | // output line should contain a maximum of OUTPUT_MAX_COLUMNS characters. | |||
264 | ||||
265 | void Options::OutputFormattedUsageText(Stream &strm, | |||
266 | const OptionDefinition &option_def, | |||
267 | uint32_t output_max_columns) { | |||
268 | std::string actual_text; | |||
269 | if (option_def.validator) { | |||
270 | const char *condition = option_def.validator->ShortConditionString(); | |||
271 | if (condition) { | |||
272 | actual_text = "["; | |||
273 | actual_text.append(condition); | |||
274 | actual_text.append("] "); | |||
275 | } | |||
276 | } | |||
277 | actual_text.append(option_def.usage_text); | |||
278 | ||||
279 | // Will it all fit on one line? | |||
280 | ||||
281 | if (static_cast<uint32_t>(actual_text.length() + strm.GetIndentLevel()) < | |||
282 | output_max_columns) { | |||
283 | // Output it as a single line. | |||
284 | strm.Indent(actual_text); | |||
285 | strm.EOL(); | |||
286 | } else { | |||
287 | // We need to break it up into multiple lines. | |||
288 | ||||
289 | int text_width = output_max_columns - strm.GetIndentLevel() - 1; | |||
290 | int start = 0; | |||
291 | int end = start; | |||
292 | int final_end = actual_text.length(); | |||
293 | int sub_len; | |||
294 | ||||
295 | while (end < final_end) { | |||
296 | // Don't start the 'text' on a space, since we're already outputting the | |||
297 | // indentation. | |||
298 | while ((start < final_end) && (actual_text[start] == ' ')) | |||
299 | start++; | |||
300 | ||||
301 | end = start + text_width; | |||
302 | if (end > final_end) | |||
303 | end = final_end; | |||
304 | else { | |||
305 | // If we're not at the end of the text, make sure we break the line on | |||
306 | // white space. | |||
307 | while (end > start && actual_text[end] != ' ' && | |||
308 | actual_text[end] != '\t' && actual_text[end] != '\n') | |||
309 | end--; | |||
310 | } | |||
311 | ||||
312 | sub_len = end - start; | |||
313 | if (start != 0) | |||
314 | strm.EOL(); | |||
315 | strm.Indent(); | |||
316 | assert(start < final_end)(static_cast <bool> (start < final_end) ? void (0) : __assert_fail ("start < final_end", "lldb/source/Interpreter/Options.cpp" , 316, __extension__ __PRETTY_FUNCTION__)); | |||
317 | assert(start + sub_len <= final_end)(static_cast <bool> (start + sub_len <= final_end) ? void (0) : __assert_fail ("start + sub_len <= final_end", "lldb/source/Interpreter/Options.cpp", 317, __extension__ __PRETTY_FUNCTION__ )); | |||
318 | strm.Write(actual_text.c_str() + start, sub_len); | |||
319 | start = end + 1; | |||
320 | } | |||
321 | strm.EOL(); | |||
322 | } | |||
323 | } | |||
324 | ||||
325 | bool Options::SupportsLongOption(const char *long_option) { | |||
326 | if (!long_option || !long_option[0]) | |||
327 | return false; | |||
328 | ||||
329 | auto opt_defs = GetDefinitions(); | |||
330 | if (opt_defs.empty()) | |||
331 | return false; | |||
332 | ||||
333 | const char *long_option_name = long_option; | |||
334 | if (long_option[0] == '-' && long_option[1] == '-') | |||
335 | long_option_name += 2; | |||
336 | ||||
337 | for (auto &def : opt_defs) { | |||
338 | if (!def.long_option) | |||
339 | continue; | |||
340 | ||||
341 | if (strcmp(def.long_option, long_option_name) == 0) | |||
342 | return true; | |||
343 | } | |||
344 | ||||
345 | return false; | |||
346 | } | |||
347 | ||||
348 | enum OptionDisplayType { | |||
349 | eDisplayBestOption, | |||
350 | eDisplayShortOption, | |||
351 | eDisplayLongOption | |||
352 | }; | |||
353 | ||||
354 | static bool PrintOption(const OptionDefinition &opt_def, | |||
355 | OptionDisplayType display_type, const char *header, | |||
356 | const char *footer, bool show_optional, Stream &strm) { | |||
357 | if (display_type == eDisplayShortOption && !opt_def.HasShortOption()) | |||
358 | return false; | |||
359 | ||||
360 | if (header && header[0]) | |||
361 | strm.PutCString(header); | |||
362 | ||||
363 | if (show_optional && !opt_def.required) | |||
364 | strm.PutChar('['); | |||
365 | const bool show_short_option = | |||
366 | opt_def.HasShortOption() && display_type != eDisplayLongOption; | |||
367 | if (show_short_option) | |||
368 | strm.Printf("-%c", opt_def.short_option); | |||
369 | else | |||
370 | strm.Printf("--%s", opt_def.long_option); | |||
371 | switch (opt_def.option_has_arg) { | |||
372 | case OptionParser::eNoArgument: | |||
373 | break; | |||
374 | case OptionParser::eRequiredArgument: | |||
375 | strm.Printf(" <%s>", CommandObject::GetArgumentName(opt_def.argument_type)); | |||
376 | break; | |||
377 | ||||
378 | case OptionParser::eOptionalArgument: | |||
379 | strm.Printf("%s[<%s>]", show_short_option ? "" : "=", | |||
380 | CommandObject::GetArgumentName(opt_def.argument_type)); | |||
381 | break; | |||
382 | } | |||
383 | if (show_optional && !opt_def.required) | |||
384 | strm.PutChar(']'); | |||
385 | if (footer && footer[0]) | |||
386 | strm.PutCString(footer); | |||
387 | return true; | |||
388 | } | |||
389 | ||||
390 | void Options::GenerateOptionUsage(Stream &strm, CommandObject *cmd, | |||
391 | uint32_t screen_width) { | |||
392 | const bool only_print_args = cmd->IsDashDashCommand(); | |||
393 | ||||
394 | auto opt_defs = GetDefinitions(); | |||
395 | const uint32_t save_indent_level = strm.GetIndentLevel(); | |||
396 | llvm::StringRef name; | |||
397 | ||||
398 | StreamString arguments_str; | |||
399 | ||||
400 | if (cmd) { | |||
401 | name = cmd->GetCommandName(); | |||
402 | cmd->GetFormattedCommandArguments(arguments_str); | |||
403 | } else | |||
404 | name = ""; | |||
405 | ||||
406 | const uint32_t num_options = NumCommandOptions(); | |||
407 | if (num_options == 0) | |||
408 | return; | |||
409 | ||||
410 | if (!only_print_args) | |||
411 | strm.PutCString("\nCommand Options Usage:\n"); | |||
412 | ||||
413 | strm.IndentMore(2); | |||
414 | ||||
415 | // First, show each usage level set of options, e.g. <cmd> [options-for- | |||
416 | // level-0] | |||
417 | // <cmd> | |||
418 | // [options-for-level-1] | |||
419 | // etc. | |||
420 | ||||
421 | uint32_t num_option_sets = GetRequiredOptions().size(); | |||
422 | ||||
423 | uint32_t i; | |||
424 | ||||
425 | if (!only_print_args) { | |||
426 | for (uint32_t opt_set = 0; opt_set < num_option_sets; ++opt_set) { | |||
427 | uint32_t opt_set_mask; | |||
428 | ||||
429 | opt_set_mask = 1 << opt_set; | |||
430 | if (opt_set > 0) | |||
431 | strm.Printf("\n"); | |||
432 | strm.Indent(name); | |||
433 | ||||
434 | // Different option sets may require different args. | |||
435 | StreamString args_str; | |||
436 | if (cmd) | |||
437 | cmd->GetFormattedCommandArguments(args_str, opt_set_mask); | |||
438 | ||||
439 | // First go through and print all options that take no arguments as a | |||
440 | // single string. If a command has "-a" "-b" and "-c", this will show up | |||
441 | // as [-abc] | |||
442 | ||||
443 | std::set<int> options; | |||
444 | std::set<int>::const_iterator options_pos, options_end; | |||
445 | for (auto &def : opt_defs) { | |||
446 | if (def.usage_mask & opt_set_mask && def.HasShortOption()) { | |||
447 | // Add current option to the end of out_stream. | |||
448 | ||||
449 | if (def.required && def.option_has_arg == OptionParser::eNoArgument) { | |||
450 | options.insert(def.short_option); | |||
451 | } | |||
452 | } | |||
453 | } | |||
454 | ||||
455 | if (!options.empty()) { | |||
456 | // We have some required options with no arguments | |||
457 | strm.PutCString(" -"); | |||
458 | for (i = 0; i < 2; ++i) | |||
459 | for (options_pos = options.begin(), options_end = options.end(); | |||
460 | options_pos != options_end; ++options_pos) { | |||
461 | if (i == 0 && ::islower(*options_pos)) | |||
462 | continue; | |||
463 | if (i == 1 && ::isupper(*options_pos)) | |||
464 | continue; | |||
465 | strm << (char)*options_pos; | |||
466 | } | |||
467 | } | |||
468 | ||||
469 | options.clear(); | |||
470 | for (auto &def : opt_defs) { | |||
471 | if (def.usage_mask & opt_set_mask && def.HasShortOption()) { | |||
472 | // Add current option to the end of out_stream. | |||
473 | ||||
474 | if (!def.required && | |||
475 | def.option_has_arg == OptionParser::eNoArgument) { | |||
476 | options.insert(def.short_option); | |||
477 | } | |||
478 | } | |||
479 | } | |||
480 | ||||
481 | if (!options.empty()) { | |||
482 | // We have some required options with no arguments | |||
483 | strm.PutCString(" [-"); | |||
484 | for (i = 0; i < 2; ++i) | |||
485 | for (options_pos = options.begin(), options_end = options.end(); | |||
486 | options_pos != options_end; ++options_pos) { | |||
487 | if (i == 0 && ::islower(*options_pos)) | |||
488 | continue; | |||
489 | if (i == 1 && ::isupper(*options_pos)) | |||
490 | continue; | |||
491 | strm << (char)*options_pos; | |||
492 | } | |||
493 | strm.PutChar(']'); | |||
494 | } | |||
495 | ||||
496 | // First go through and print the required options (list them up front). | |||
497 | ||||
498 | for (auto &def : opt_defs) { | |||
499 | if (def.usage_mask & opt_set_mask && def.HasShortOption()) { | |||
500 | if (def.required && def.option_has_arg != OptionParser::eNoArgument) | |||
501 | PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm); | |||
502 | } | |||
503 | } | |||
504 | ||||
505 | // Now go through again, and this time only print the optional options. | |||
506 | ||||
507 | for (auto &def : opt_defs) { | |||
508 | if (def.usage_mask & opt_set_mask) { | |||
509 | // Add current option to the end of out_stream. | |||
510 | ||||
511 | if (!def.required && def.option_has_arg != OptionParser::eNoArgument) | |||
512 | PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm); | |||
513 | } | |||
514 | } | |||
515 | ||||
516 | if (args_str.GetSize() > 0) { | |||
517 | if (cmd->WantsRawCommandString() && !only_print_args) | |||
518 | strm.Printf(" --"); | |||
519 | ||||
520 | strm << " " << args_str.GetString(); | |||
521 | if (only_print_args) | |||
522 | break; | |||
523 | } | |||
524 | } | |||
525 | } | |||
526 | ||||
527 | if (cmd && (only_print_args || cmd->WantsRawCommandString()) && | |||
528 | arguments_str.GetSize() > 0) { | |||
529 | if (!only_print_args) | |||
530 | strm.PutChar('\n'); | |||
531 | strm.Indent(name); | |||
532 | strm << " " << arguments_str.GetString(); | |||
533 | } | |||
534 | ||||
535 | if (!only_print_args) { | |||
536 | strm.Printf("\n\n"); | |||
537 | ||||
538 | // Now print out all the detailed information about the various options: | |||
539 | // long form, short form and help text: | |||
540 | // -short <argument> ( --long_name <argument> ) | |||
541 | // help text | |||
542 | ||||
543 | // This variable is used to keep track of which options' info we've printed | |||
544 | // out, because some options can be in more than one usage level, but we | |||
545 | // only want to print the long form of its information once. | |||
546 | ||||
547 | std::multimap<int, uint32_t> options_seen; | |||
548 | strm.IndentMore(5); | |||
549 | ||||
550 | // Put the unique command options in a vector & sort it, so we can output | |||
551 | // them alphabetically (by short_option) when writing out detailed help for | |||
552 | // each option. | |||
553 | ||||
554 | i = 0; | |||
555 | for (auto &def : opt_defs) | |||
556 | options_seen.insert(std::make_pair(def.short_option, i++)); | |||
557 | ||||
558 | // Go through the unique'd and alphabetically sorted vector of options, | |||
559 | // find the table entry for each option and write out the detailed help | |||
560 | // information for that option. | |||
561 | ||||
562 | bool first_option_printed = false; | |||
563 | ||||
564 | for (auto pos : options_seen) { | |||
565 | i = pos.second; | |||
566 | // Print out the help information for this option. | |||
567 | ||||
568 | // Put a newline separation between arguments | |||
569 | if (first_option_printed) | |||
570 | strm.EOL(); | |||
571 | else | |||
572 | first_option_printed = true; | |||
573 | ||||
574 | CommandArgumentType arg_type = opt_defs[i].argument_type; | |||
575 | ||||
576 | StreamString arg_name_str; | |||
577 | arg_name_str.Printf("<%s>", CommandObject::GetArgumentName(arg_type)); | |||
578 | ||||
579 | strm.Indent(); | |||
580 | if (opt_defs[i].short_option && opt_defs[i].HasShortOption()) { | |||
581 | PrintOption(opt_defs[i], eDisplayShortOption, nullptr, nullptr, false, | |||
582 | strm); | |||
583 | PrintOption(opt_defs[i], eDisplayLongOption, " ( ", " )", false, strm); | |||
584 | } else { | |||
585 | // Short option is not printable, just print long option | |||
586 | PrintOption(opt_defs[i], eDisplayLongOption, nullptr, nullptr, false, | |||
587 | strm); | |||
588 | } | |||
589 | strm.EOL(); | |||
590 | ||||
591 | strm.IndentMore(5); | |||
592 | ||||
593 | if (opt_defs[i].usage_text) | |||
594 | OutputFormattedUsageText(strm, opt_defs[i], screen_width); | |||
595 | if (!opt_defs[i].enum_values.empty()) { | |||
596 | strm.Indent(); | |||
597 | strm.Printf("Values: "); | |||
598 | bool is_first = true; | |||
599 | for (const auto &enum_value : opt_defs[i].enum_values) { | |||
600 | if (is_first) { | |||
601 | strm.Printf("%s", enum_value.string_value); | |||
602 | is_first = false; | |||
603 | } | |||
604 | else | |||
605 | strm.Printf(" | %s", enum_value.string_value); | |||
606 | } | |||
607 | strm.EOL(); | |||
608 | } | |||
609 | strm.IndentLess(5); | |||
610 | } | |||
611 | } | |||
612 | ||||
613 | // Restore the indent level | |||
614 | strm.SetIndentLevel(save_indent_level); | |||
615 | } | |||
616 | ||||
617 | // This function is called when we have been given a potentially incomplete set | |||
618 | // of options, such as when an alias has been defined (more options might be | |||
619 | // added at at the time the alias is invoked). We need to verify that the | |||
620 | // options in the set m_seen_options are all part of a set that may be used | |||
621 | // together, but m_seen_options may be missing some of the "required" options. | |||
622 | ||||
623 | bool Options::VerifyPartialOptions(CommandReturnObject &result) { | |||
624 | bool options_are_valid = false; | |||
625 | ||||
626 | int num_levels = GetRequiredOptions().size(); | |||
627 | if (num_levels) { | |||
628 | for (int i = 0; i < num_levels && !options_are_valid; ++i) { | |||
629 | // In this case we are treating all options as optional rather than | |||
630 | // required. Therefore a set of options is correct if m_seen_options is a | |||
631 | // subset of the union of m_required_options and m_optional_options. | |||
632 | OptionSet union_set; | |||
633 | OptionsSetUnion(GetRequiredOptions()[i], GetOptionalOptions()[i], | |||
634 | union_set); | |||
635 | if (IsASubset(m_seen_options, union_set)) | |||
636 | options_are_valid = true; | |||
637 | } | |||
638 | } | |||
639 | ||||
640 | return options_are_valid; | |||
641 | } | |||
642 | ||||
643 | bool Options::HandleOptionCompletion(CompletionRequest &request, | |||
644 | OptionElementVector &opt_element_vector, | |||
645 | CommandInterpreter &interpreter) { | |||
646 | // For now we just scan the completions to see if the cursor position is in | |||
647 | // an option or its argument. Otherwise we'll call HandleArgumentCompletion. | |||
648 | // In the future we can use completion to validate options as well if we | |||
649 | // want. | |||
650 | ||||
651 | auto opt_defs = GetDefinitions(); | |||
652 | ||||
653 | llvm::StringRef cur_opt_str = request.GetCursorArgumentPrefix(); | |||
654 | ||||
655 | for (size_t i = 0; i < opt_element_vector.size(); i++) { | |||
656 | size_t opt_pos = static_cast<size_t>(opt_element_vector[i].opt_pos); | |||
657 | size_t opt_arg_pos = static_cast<size_t>(opt_element_vector[i].opt_arg_pos); | |||
658 | int opt_defs_index = opt_element_vector[i].opt_defs_index; | |||
659 | if (opt_pos == request.GetCursorIndex()) { | |||
660 | // We're completing the option itself. | |||
661 | ||||
662 | if (opt_defs_index == OptionArgElement::eBareDash) { | |||
663 | // We're completing a bare dash. That means all options are open. | |||
664 | // FIXME: We should scan the other options provided and only complete | |||
665 | // options | |||
666 | // within the option group they belong to. | |||
667 | std::string opt_str = "-a"; | |||
668 | ||||
669 | for (auto &def : opt_defs) { | |||
670 | if (!def.short_option) | |||
671 | continue; | |||
672 | opt_str[1] = def.short_option; | |||
673 | request.AddCompletion(opt_str, def.usage_text); | |||
674 | } | |||
675 | ||||
676 | return true; | |||
677 | } else if (opt_defs_index == OptionArgElement::eBareDoubleDash) { | |||
678 | std::string full_name("--"); | |||
679 | for (auto &def : opt_defs) { | |||
680 | if (!def.short_option) | |||
681 | continue; | |||
682 | ||||
683 | full_name.erase(full_name.begin() + 2, full_name.end()); | |||
684 | full_name.append(def.long_option); | |||
685 | request.AddCompletion(full_name, def.usage_text); | |||
686 | } | |||
687 | return true; | |||
688 | } else if (opt_defs_index != OptionArgElement::eUnrecognizedArg) { | |||
689 | // We recognized it, if it an incomplete long option, complete it | |||
690 | // anyway (getopt_long_only is happy with shortest unique string, but | |||
691 | // it's still a nice thing to do.) Otherwise return The string so the | |||
692 | // upper level code will know this is a full match and add the " ". | |||
693 | const OptionDefinition &opt = opt_defs[opt_defs_index]; | |||
694 | llvm::StringRef long_option = opt.long_option; | |||
695 | if (cur_opt_str.startswith("--") && cur_opt_str != long_option) { | |||
696 | request.AddCompletion("--" + long_option.str(), opt.usage_text); | |||
697 | return true; | |||
698 | } else | |||
699 | request.AddCompletion(request.GetCursorArgumentPrefix()); | |||
700 | return true; | |||
701 | } else { | |||
702 | // FIXME - not handling wrong options yet: | |||
703 | // Check to see if they are writing a long option & complete it. | |||
704 | // I think we will only get in here if the long option table has two | |||
705 | // elements | |||
706 | // that are not unique up to this point. getopt_long_only does | |||
707 | // shortest unique match for long options already. | |||
708 | if (cur_opt_str.consume_front("--")) { | |||
709 | for (auto &def : opt_defs) { | |||
710 | llvm::StringRef long_option(def.long_option); | |||
711 | if (long_option.startswith(cur_opt_str)) | |||
712 | request.AddCompletion("--" + long_option.str(), def.usage_text); | |||
713 | } | |||
714 | } | |||
715 | return true; | |||
716 | } | |||
717 | ||||
718 | } else if (opt_arg_pos == request.GetCursorIndex()) { | |||
719 | // Okay the cursor is on the completion of an argument. See if it has a | |||
720 | // completion, otherwise return no matches. | |||
721 | if (opt_defs_index != -1) { | |||
722 | HandleOptionArgumentCompletion(request, opt_element_vector, i, | |||
723 | interpreter); | |||
724 | return true; | |||
725 | } else { | |||
726 | // No completion callback means no completions... | |||
727 | return true; | |||
728 | } | |||
729 | ||||
730 | } else { | |||
731 | // Not the last element, keep going. | |||
732 | continue; | |||
733 | } | |||
734 | } | |||
735 | return false; | |||
736 | } | |||
737 | ||||
738 | void Options::HandleOptionArgumentCompletion( | |||
739 | CompletionRequest &request, OptionElementVector &opt_element_vector, | |||
740 | int opt_element_index, CommandInterpreter &interpreter) { | |||
741 | auto opt_defs = GetDefinitions(); | |||
742 | std::unique_ptr<SearchFilter> filter_up; | |||
743 | ||||
744 | int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index; | |||
745 | ||||
746 | // See if this is an enumeration type option, and if so complete it here: | |||
747 | ||||
748 | const auto &enum_values = opt_defs[opt_defs_index].enum_values; | |||
749 | if (!enum_values.empty()) | |||
750 | for (const auto &enum_value : enum_values) | |||
751 | request.TryCompleteCurrentArg(enum_value.string_value); | |||
752 | ||||
753 | // If this is a source file or symbol type completion, and there is a -shlib | |||
754 | // option somewhere in the supplied arguments, then make a search filter for | |||
755 | // that shared library. | |||
756 | // FIXME: Do we want to also have an "OptionType" so we don't have to match | |||
757 | // string names? | |||
758 | ||||
759 | uint32_t completion_mask = opt_defs[opt_defs_index].completion_type; | |||
760 | ||||
761 | if (completion_mask == 0) { | |||
762 | lldb::CommandArgumentType option_arg_type = | |||
763 | opt_defs[opt_defs_index].argument_type; | |||
764 | if (option_arg_type != eArgTypeNone) { | |||
765 | const CommandObject::ArgumentTableEntry *arg_entry = | |||
766 | CommandObject::FindArgumentDataByType( | |||
767 | opt_defs[opt_defs_index].argument_type); | |||
768 | if (arg_entry) | |||
769 | completion_mask = arg_entry->completion_type; | |||
770 | } | |||
771 | } | |||
772 | ||||
773 | if (completion_mask & CommandCompletions::eSourceFileCompletion || | |||
774 | completion_mask & CommandCompletions::eSymbolCompletion) { | |||
775 | for (size_t i = 0; i < opt_element_vector.size(); i++) { | |||
776 | int cur_defs_index = opt_element_vector[i].opt_defs_index; | |||
777 | ||||
778 | // trying to use <0 indices will definitely cause problems | |||
779 | if (cur_defs_index == OptionArgElement::eUnrecognizedArg || | |||
780 | cur_defs_index == OptionArgElement::eBareDash || | |||
781 | cur_defs_index == OptionArgElement::eBareDoubleDash) | |||
782 | continue; | |||
783 | ||||
784 | int cur_arg_pos = opt_element_vector[i].opt_arg_pos; | |||
785 | const char *cur_opt_name = opt_defs[cur_defs_index].long_option; | |||
786 | ||||
787 | // If this is the "shlib" option and there was an argument provided, | |||
788 | // restrict it to that shared library. | |||
789 | if (cur_opt_name && strcmp(cur_opt_name, "shlib") == 0 && | |||
790 | cur_arg_pos != -1) { | |||
791 | const char *module_name = | |||
792 | request.GetParsedLine().GetArgumentAtIndex(cur_arg_pos); | |||
793 | if (module_name) { | |||
794 | FileSpec module_spec(module_name); | |||
795 | lldb::TargetSP target_sp = | |||
796 | interpreter.GetDebugger().GetSelectedTarget(); | |||
797 | // Search filters require a target... | |||
798 | if (target_sp) | |||
799 | filter_up = | |||
800 | std::make_unique<SearchFilterByModule>(target_sp, module_spec); | |||
801 | } | |||
802 | break; | |||
803 | } | |||
804 | } | |||
805 | } | |||
806 | ||||
807 | CommandCompletions::InvokeCommonCompletionCallbacks( | |||
808 | interpreter, completion_mask, request, filter_up.get()); | |||
809 | } | |||
810 | ||||
811 | void OptionGroupOptions::Append(OptionGroup *group) { | |||
812 | auto group_option_defs = group->GetDefinitions(); | |||
813 | for (uint32_t i = 0; i < group_option_defs.size(); ++i) { | |||
814 | m_option_infos.push_back(OptionInfo(group, i)); | |||
815 | m_option_defs.push_back(group_option_defs[i]); | |||
816 | } | |||
817 | } | |||
818 | ||||
819 | const OptionGroup *OptionGroupOptions::GetGroupWithOption(char short_opt) { | |||
820 | for (uint32_t i = 0; i < m_option_defs.size(); i++) { | |||
821 | OptionDefinition opt_def = m_option_defs[i]; | |||
822 | if (opt_def.short_option == short_opt) | |||
823 | return m_option_infos[i].option_group; | |||
824 | } | |||
825 | return nullptr; | |||
826 | } | |||
827 | ||||
828 | void OptionGroupOptions::Append(OptionGroup *group, uint32_t src_mask, | |||
829 | uint32_t dst_mask) { | |||
830 | auto group_option_defs = group->GetDefinitions(); | |||
831 | for (uint32_t i = 0; i < group_option_defs.size(); ++i) { | |||
832 | if (group_option_defs[i].usage_mask & src_mask) { | |||
833 | m_option_infos.push_back(OptionInfo(group, i)); | |||
834 | m_option_defs.push_back(group_option_defs[i]); | |||
835 | m_option_defs.back().usage_mask = dst_mask; | |||
836 | } | |||
837 | } | |||
838 | } | |||
839 | ||||
840 | void OptionGroupOptions::Finalize() { | |||
841 | m_did_finalize = true; | |||
842 | } | |||
843 | ||||
844 | Status OptionGroupOptions::SetOptionValue(uint32_t option_idx, | |||
845 | llvm::StringRef option_value, | |||
846 | ExecutionContext *execution_context) { | |||
847 | // After calling OptionGroupOptions::Append(...), you must finalize the | |||
848 | // groups by calling OptionGroupOptions::Finlize() | |||
849 | assert(m_did_finalize)(static_cast <bool> (m_did_finalize) ? void (0) : __assert_fail ("m_did_finalize", "lldb/source/Interpreter/Options.cpp", 849 , __extension__ __PRETTY_FUNCTION__)); | |||
850 | Status error; | |||
851 | if (option_idx < m_option_infos.size()) { | |||
852 | error = m_option_infos[option_idx].option_group->SetOptionValue( | |||
853 | m_option_infos[option_idx].option_index, option_value, | |||
854 | execution_context); | |||
855 | ||||
856 | } else { | |||
857 | error.SetErrorString("invalid option index"); // Shouldn't happen... | |||
858 | } | |||
859 | return error; | |||
860 | } | |||
861 | ||||
862 | void OptionGroupOptions::OptionParsingStarting( | |||
863 | ExecutionContext *execution_context) { | |||
864 | std::set<OptionGroup *> group_set; | |||
865 | OptionInfos::iterator pos, end = m_option_infos.end(); | |||
866 | for (pos = m_option_infos.begin(); pos != end; ++pos) { | |||
867 | OptionGroup *group = pos->option_group; | |||
868 | if (group_set.find(group) == group_set.end()) { | |||
869 | group->OptionParsingStarting(execution_context); | |||
870 | group_set.insert(group); | |||
871 | } | |||
872 | } | |||
873 | } | |||
874 | Status | |||
875 | OptionGroupOptions::OptionParsingFinished(ExecutionContext *execution_context) { | |||
876 | std::set<OptionGroup *> group_set; | |||
877 | Status error; | |||
878 | OptionInfos::iterator pos, end = m_option_infos.end(); | |||
879 | for (pos = m_option_infos.begin(); pos != end; ++pos) { | |||
880 | OptionGroup *group = pos->option_group; | |||
881 | if (group_set.find(group) == group_set.end()) { | |||
882 | error = group->OptionParsingFinished(execution_context); | |||
883 | group_set.insert(group); | |||
884 | if (error.Fail()) | |||
885 | return error; | |||
886 | } | |||
887 | } | |||
888 | return error; | |||
889 | } | |||
890 | ||||
891 | // OptionParser permutes the arguments while processing them, so we create a | |||
892 | // temporary array holding to avoid modification of the input arguments. The | |||
893 | // options themselves are never modified, but the API expects a char * anyway, | |||
894 | // hence the const_cast. | |||
895 | static std::vector<char *> GetArgvForParsing(const Args &args) { | |||
896 | std::vector<char *> result; | |||
897 | // OptionParser always skips the first argument as it is based on getopt(). | |||
898 | result.push_back(const_cast<char *>("<FAKE-ARG0>")); | |||
899 | for (const Args::ArgEntry &entry : args) | |||
900 | result.push_back(const_cast<char *>(entry.c_str())); | |||
901 | result.push_back(nullptr); | |||
902 | return result; | |||
903 | } | |||
904 | ||||
905 | // Given a permuted argument, find it's position in the original Args vector. | |||
906 | static Args::const_iterator FindOriginalIter(const char *arg, | |||
907 | const Args &original) { | |||
908 | return llvm::find_if( | |||
909 | original, [arg](const Args::ArgEntry &D) { return D.c_str() == arg; }); | |||
910 | } | |||
911 | ||||
912 | // Given a permuted argument, find it's index in the original Args vector. | |||
913 | static size_t FindOriginalIndex(const char *arg, const Args &original) { | |||
914 | return std::distance(original.begin(), FindOriginalIter(arg, original)); | |||
915 | } | |||
916 | ||||
917 | // Construct a new Args object, consisting of the entries from the original | |||
918 | // arguments, but in the permuted order. | |||
919 | static Args ReconstituteArgsAfterParsing(llvm::ArrayRef<char *> parsed, | |||
920 | const Args &original) { | |||
921 | Args result; | |||
922 | for (const char *arg : parsed) { | |||
923 | auto pos = FindOriginalIter(arg, original); | |||
924 | assert(pos != original.end())(static_cast <bool> (pos != original.end()) ? void (0) : __assert_fail ("pos != original.end()", "lldb/source/Interpreter/Options.cpp" , 924, __extension__ __PRETTY_FUNCTION__)); | |||
925 | result.AppendArgument(pos->ref(), pos->GetQuoteChar()); | |||
926 | } | |||
927 | return result; | |||
928 | } | |||
929 | ||||
930 | static size_t FindArgumentIndexForOption(const Args &args, | |||
931 | const Option &long_option) { | |||
932 | std::string short_opt = llvm::formatv("-{0}", char(long_option.val)).str(); | |||
933 | std::string long_opt = | |||
934 | std::string(llvm::formatv("--{0}", long_option.definition->long_option)); | |||
| ||||
935 | for (const auto &entry : llvm::enumerate(args)) { | |||
936 | if (entry.value().ref().startswith(short_opt) || | |||
937 | entry.value().ref().startswith(long_opt)) | |||
938 | return entry.index(); | |||
939 | } | |||
940 | ||||
941 | return size_t(-1); | |||
942 | } | |||
943 | ||||
944 | static std::string BuildShortOptions(const Option *long_options) { | |||
945 | std::string storage; | |||
946 | llvm::raw_string_ostream sstr(storage); | |||
947 | ||||
948 | // Leading : tells getopt to return a : for a missing option argument AND to | |||
949 | // suppress error messages. | |||
950 | sstr << ":"; | |||
951 | ||||
952 | for (size_t i = 0; long_options[i].definition != nullptr; ++i) { | |||
953 | if (long_options[i].flag == nullptr) { | |||
954 | sstr << (char)long_options[i].val; | |||
955 | switch (long_options[i].definition->option_has_arg) { | |||
956 | default: | |||
957 | case OptionParser::eNoArgument: | |||
958 | break; | |||
959 | case OptionParser::eRequiredArgument: | |||
960 | sstr << ":"; | |||
961 | break; | |||
962 | case OptionParser::eOptionalArgument: | |||
963 | sstr << "::"; | |||
964 | break; | |||
965 | } | |||
966 | } | |||
967 | } | |||
968 | return std::move(sstr.str()); | |||
969 | } | |||
970 | ||||
971 | llvm::Expected<Args> Options::ParseAlias(const Args &args, | |||
972 | OptionArgVector *option_arg_vector, | |||
973 | std::string &input_line) { | |||
974 | Option *long_options = GetLongOptions(); | |||
975 | ||||
976 | if (long_options == nullptr) { | |||
| ||||
977 | return llvm::make_error<llvm::StringError>("Invalid long options", | |||
978 | llvm::inconvertibleErrorCode()); | |||
979 | } | |||
980 | ||||
981 | std::string short_options = BuildShortOptions(long_options); | |||
982 | ||||
983 | Args args_copy = args; | |||
984 | std::vector<char *> argv = GetArgvForParsing(args); | |||
985 | ||||
986 | std::unique_lock<std::mutex> lock; | |||
987 | OptionParser::Prepare(lock); | |||
988 | int val; | |||
989 | while (true) { | |||
990 | int long_options_index = -1; | |||
991 | val = OptionParser::Parse(argv, short_options, long_options, | |||
992 | &long_options_index); | |||
993 | ||||
994 | if (val == ':') { | |||
995 | return llvm::createStringError(llvm::inconvertibleErrorCode(), | |||
996 | "last option requires an argument"); | |||
997 | } | |||
998 | ||||
999 | if (val == -1) | |||
1000 | break; | |||
1001 | ||||
1002 | if (val == '?') { | |||
1003 | return llvm::make_error<llvm::StringError>( | |||
1004 | "Unknown or ambiguous option", llvm::inconvertibleErrorCode()); | |||
1005 | } | |||
1006 | ||||
1007 | if (val == 0) | |||
1008 | continue; | |||
1009 | ||||
1010 | OptionSeen(val); | |||
1011 | ||||
1012 | // Look up the long option index | |||
1013 | if (long_options_index == -1) { | |||
1014 | for (int j = 0; long_options[j].definition || long_options[j].flag || | |||
1015 | long_options[j].val; | |||
1016 | ++j) { | |||
1017 | if (long_options[j].val == val) { | |||
1018 | long_options_index = j; | |||
1019 | break; | |||
1020 | } | |||
1021 | } | |||
1022 | } | |||
1023 | ||||
1024 | // See if the option takes an argument, and see if one was supplied. | |||
1025 | if (long_options_index == -1) { | |||
1026 | return llvm::make_error<llvm::StringError>( | |||
1027 | llvm::formatv("Invalid option with value '{0}'.", char(val)).str(), | |||
1028 | llvm::inconvertibleErrorCode()); | |||
1029 | } | |||
1030 | ||||
1031 | StreamString option_str; | |||
1032 | option_str.Printf("-%c", val); | |||
1033 | const OptionDefinition *def = long_options[long_options_index].definition; | |||
1034 | int has_arg = | |||
1035 | (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg; | |||
1036 | ||||
1037 | const char *option_arg = nullptr; | |||
1038 | switch (has_arg) { | |||
1039 | case OptionParser::eRequiredArgument: | |||
1040 | if (OptionParser::GetOptionArgument() == nullptr) { | |||
1041 | return llvm::make_error<llvm::StringError>( | |||
1042 | llvm::formatv("Option '{0}' is missing argument specifier.", | |||
1043 | option_str.GetString()) | |||
1044 | .str(), | |||
1045 | llvm::inconvertibleErrorCode()); | |||
1046 | } | |||
1047 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
1048 | case OptionParser::eOptionalArgument: | |||
1049 | option_arg = OptionParser::GetOptionArgument(); | |||
1050 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
1051 | case OptionParser::eNoArgument: | |||
1052 | break; | |||
1053 | default: | |||
1054 | return llvm::make_error<llvm::StringError>( | |||
1055 | llvm::formatv("error with options table; invalid value in has_arg " | |||
1056 | "field for option '{0}'.", | |||
1057 | char(val)) | |||
1058 | .str(), | |||
1059 | llvm::inconvertibleErrorCode()); | |||
1060 | } | |||
1061 | if (!option_arg
| |||
1062 | option_arg = "<no-argument>"; | |||
1063 | option_arg_vector->emplace_back(std::string(option_str.GetString()), | |||
1064 | has_arg, std::string(option_arg)); | |||
1065 | ||||
1066 | // Find option in the argument list; also see if it was supposed to take an | |||
1067 | // argument and if one was supplied. Remove option (and argument, if | |||
1068 | // given) from the argument list. Also remove them from the | |||
1069 | // raw_input_string, if one was passed in. | |||
1070 | size_t idx = | |||
1071 | FindArgumentIndexForOption(args_copy, long_options[long_options_index]); | |||
1072 | if (idx == size_t(-1)) | |||
1073 | continue; | |||
1074 | ||||
1075 | if (!input_line.empty()) { | |||
1076 | auto tmp_arg = args_copy[idx].ref(); | |||
1077 | size_t pos = input_line.find(std::string(tmp_arg)); | |||
1078 | if (pos != std::string::npos) | |||
1079 | input_line.erase(pos, tmp_arg.size()); | |||
1080 | } | |||
1081 | args_copy.DeleteArgumentAtIndex(idx); | |||
1082 | if ((long_options[long_options_index].definition->option_has_arg != | |||
1083 | OptionParser::eNoArgument) && | |||
1084 | (OptionParser::GetOptionArgument() != nullptr) && | |||
1085 | (idx < args_copy.GetArgumentCount()) && | |||
1086 | (args_copy[idx].ref() == OptionParser::GetOptionArgument())) { | |||
1087 | if (input_line.size() > 0) { | |||
1088 | auto tmp_arg = args_copy[idx].ref(); | |||
1089 | size_t pos = input_line.find(std::string(tmp_arg)); | |||
1090 | if (pos != std::string::npos) | |||
1091 | input_line.erase(pos, tmp_arg.size()); | |||
1092 | } | |||
1093 | args_copy.DeleteArgumentAtIndex(idx); | |||
1094 | } | |||
1095 | } | |||
1096 | ||||
1097 | return std::move(args_copy); | |||
1098 | } | |||
1099 | ||||
1100 | OptionElementVector Options::ParseForCompletion(const Args &args, | |||
1101 | uint32_t cursor_index) { | |||
1102 | OptionElementVector option_element_vector; | |||
1103 | Option *long_options = GetLongOptions(); | |||
1104 | option_element_vector.clear(); | |||
1105 | ||||
1106 | if (long_options == nullptr) | |||
1107 | return option_element_vector; | |||
1108 | ||||
1109 | std::string short_options = BuildShortOptions(long_options); | |||
1110 | ||||
1111 | std::unique_lock<std::mutex> lock; | |||
1112 | OptionParser::Prepare(lock); | |||
1113 | OptionParser::EnableError(false); | |||
1114 | ||||
1115 | int val; | |||
1116 | auto opt_defs = GetDefinitions(); | |||
1117 | ||||
1118 | std::vector<char *> dummy_vec = GetArgvForParsing(args); | |||
1119 | ||||
1120 | bool failed_once = false; | |||
1121 | uint32_t dash_dash_pos = -1; | |||
1122 | ||||
1123 | while (true) { | |||
1124 | bool missing_argument = false; | |||
1125 | int long_options_index = -1; | |||
1126 | ||||
1127 | val = OptionParser::Parse(dummy_vec, short_options, long_options, | |||
1128 | &long_options_index); | |||
1129 | ||||
1130 | if (val == -1) { | |||
1131 | // When we're completing a "--" which is the last option on line, | |||
1132 | if (failed_once) | |||
1133 | break; | |||
1134 | ||||
1135 | failed_once = true; | |||
1136 | ||||
1137 | // If this is a bare "--" we mark it as such so we can complete it | |||
1138 | // successfully later. Handling the "--" is a little tricky, since that | |||
1139 | // may mean end of options or arguments, or the user might want to | |||
1140 | // complete options by long name. I make this work by checking whether | |||
1141 | // the cursor is in the "--" argument, and if so I assume we're | |||
1142 | // completing the long option, otherwise I let it pass to | |||
1143 | // OptionParser::Parse which will terminate the option parsing. Note, in | |||
1144 | // either case we continue parsing the line so we can figure out what | |||
1145 | // other options were passed. This will be useful when we come to | |||
1146 | // restricting completions based on what other options we've seen on the | |||
1147 | // line. | |||
1148 | ||||
1149 | if (static_cast<size_t>(OptionParser::GetOptionIndex()) < | |||
1150 | dummy_vec.size() && | |||
1151 | (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) { | |||
1152 | dash_dash_pos = FindOriginalIndex( | |||
1153 | dummy_vec[OptionParser::GetOptionIndex() - 1], args); | |||
1154 | if (dash_dash_pos == cursor_index) { | |||
1155 | option_element_vector.push_back( | |||
1156 | OptionArgElement(OptionArgElement::eBareDoubleDash, dash_dash_pos, | |||
1157 | OptionArgElement::eBareDoubleDash)); | |||
1158 | continue; | |||
1159 | } else | |||
1160 | break; | |||
1161 | } else | |||
1162 | break; | |||
1163 | } else if (val == '?') { | |||
1164 | option_element_vector.push_back(OptionArgElement( | |||
1165 | OptionArgElement::eUnrecognizedArg, | |||
1166 | FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1], | |||
1167 | args), | |||
1168 | OptionArgElement::eUnrecognizedArg)); | |||
1169 | continue; | |||
1170 | } else if (val == 0) { | |||
1171 | continue; | |||
1172 | } else if (val == ':') { | |||
1173 | // This is a missing argument. | |||
1174 | val = OptionParser::GetOptionErrorCause(); | |||
1175 | missing_argument = true; | |||
1176 | } | |||
1177 | ||||
1178 | OptionSeen(val); | |||
1179 | ||||
1180 | // Look up the long option index | |||
1181 | if (long_options_index == -1) { | |||
1182 | for (int j = 0; long_options[j].definition || long_options[j].flag || | |||
1183 | long_options[j].val; | |||
1184 | ++j) { | |||
1185 | if (long_options[j].val == val) { | |||
1186 | long_options_index = j; | |||
1187 | break; | |||
1188 | } | |||
1189 | } | |||
1190 | } | |||
1191 | ||||
1192 | // See if the option takes an argument, and see if one was supplied. | |||
1193 | if (long_options_index >= 0) { | |||
1194 | int opt_defs_index = -1; | |||
1195 | for (size_t i = 0; i < opt_defs.size(); i++) { | |||
1196 | if (opt_defs[i].short_option != val) | |||
1197 | continue; | |||
1198 | opt_defs_index = i; | |||
1199 | break; | |||
1200 | } | |||
1201 | ||||
1202 | const OptionDefinition *def = long_options[long_options_index].definition; | |||
1203 | int has_arg = | |||
1204 | (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg; | |||
1205 | switch (has_arg) { | |||
1206 | case OptionParser::eNoArgument: | |||
1207 | option_element_vector.push_back(OptionArgElement( | |||
1208 | opt_defs_index, | |||
1209 | FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1], | |||
1210 | args), | |||
1211 | 0)); | |||
1212 | break; | |||
1213 | case OptionParser::eRequiredArgument: | |||
1214 | if (OptionParser::GetOptionArgument() != nullptr) { | |||
1215 | int arg_index; | |||
1216 | if (missing_argument) | |||
1217 | arg_index = -1; | |||
1218 | else | |||
1219 | arg_index = OptionParser::GetOptionIndex() - 2; | |||
1220 | ||||
1221 | option_element_vector.push_back(OptionArgElement( | |||
1222 | opt_defs_index, | |||
1223 | FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2], | |||
1224 | args), | |||
1225 | arg_index)); | |||
1226 | } else { | |||
1227 | option_element_vector.push_back(OptionArgElement( | |||
1228 | opt_defs_index, | |||
1229 | FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1], | |||
1230 | args), | |||
1231 | -1)); | |||
1232 | } | |||
1233 | break; | |||
1234 | case OptionParser::eOptionalArgument: | |||
1235 | if (OptionParser::GetOptionArgument() != nullptr) { | |||
1236 | option_element_vector.push_back(OptionArgElement( | |||
1237 | opt_defs_index, | |||
1238 | FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2], | |||
1239 | args), | |||
1240 | FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1], | |||
1241 | args))); | |||
1242 | } else { | |||
1243 | option_element_vector.push_back(OptionArgElement( | |||
1244 | opt_defs_index, | |||
1245 | FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2], | |||
1246 | args), | |||
1247 | FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1], | |||
1248 | args))); | |||
1249 | } | |||
1250 | break; | |||
1251 | default: | |||
1252 | // The options table is messed up. Here we'll just continue | |||
1253 | option_element_vector.push_back(OptionArgElement( | |||
1254 | OptionArgElement::eUnrecognizedArg, | |||
1255 | FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1], | |||
1256 | args), | |||
1257 | OptionArgElement::eUnrecognizedArg)); | |||
1258 | break; | |||
1259 | } | |||
1260 | } else { | |||
1261 | option_element_vector.push_back(OptionArgElement( | |||
1262 | OptionArgElement::eUnrecognizedArg, | |||
1263 | FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1], | |||
1264 | args), | |||
1265 | OptionArgElement::eUnrecognizedArg)); | |||
1266 | } | |||
1267 | } | |||
1268 | ||||
1269 | // Finally we have to handle the case where the cursor index points at a | |||
1270 | // single "-". We want to mark that in the option_element_vector, but only | |||
1271 | // if it is not after the "--". But it turns out that OptionParser::Parse | |||
1272 | // just ignores an isolated "-". So we have to look it up by hand here. We | |||
1273 | // only care if it is AT the cursor position. Note, a single quoted dash is | |||
1274 | // not the same as a single dash... | |||
1275 | ||||
1276 | const Args::ArgEntry &cursor = args[cursor_index]; | |||
1277 | if ((static_cast<int32_t>(dash_dash_pos) == -1 || | |||
1278 | cursor_index < dash_dash_pos) && | |||
1279 | !cursor.IsQuoted() && cursor.ref() == "-") { | |||
1280 | option_element_vector.push_back( | |||
1281 | OptionArgElement(OptionArgElement::eBareDash, cursor_index, | |||
1282 | OptionArgElement::eBareDash)); | |||
1283 | } | |||
1284 | return option_element_vector; | |||
1285 | } | |||
1286 | ||||
1287 | llvm::Expected<Args> Options::Parse(const Args &args, | |||
1288 | ExecutionContext *execution_context, | |||
1289 | lldb::PlatformSP platform_sp, | |||
1290 | bool require_validation) { | |||
1291 | Status error; | |||
1292 | Option *long_options = GetLongOptions(); | |||
1293 | if (long_options == nullptr) { | |||
1294 | return llvm::make_error<llvm::StringError>("Invalid long options.", | |||
1295 | llvm::inconvertibleErrorCode()); | |||
1296 | } | |||
1297 | ||||
1298 | std::string short_options = BuildShortOptions(long_options); | |||
1299 | std::vector<char *> argv = GetArgvForParsing(args); | |||
1300 | std::unique_lock<std::mutex> lock; | |||
1301 | OptionParser::Prepare(lock); | |||
1302 | int val; | |||
1303 | while (true) { | |||
1304 | int long_options_index = -1; | |||
1305 | val = OptionParser::Parse(argv, short_options, long_options, | |||
1306 | &long_options_index); | |||
1307 | ||||
1308 | if (val == ':') { | |||
1309 | error.SetErrorString("last option requires an argument"); | |||
1310 | break; | |||
1311 | } | |||
1312 | ||||
1313 | if (val == -1) | |||
1314 | break; | |||
1315 | ||||
1316 | // Did we get an error? | |||
1317 | if (val == '?') { | |||
1318 | error.SetErrorString("unknown or ambiguous option"); | |||
1319 | break; | |||
1320 | } | |||
1321 | // The option auto-set itself | |||
1322 | if (val == 0) | |||
1323 | continue; | |||
1324 | ||||
1325 | OptionSeen(val); | |||
1326 | ||||
1327 | // Lookup the long option index | |||
1328 | if (long_options_index == -1) { | |||
1329 | for (int i = 0; long_options[i].definition || long_options[i].flag || | |||
1330 | long_options[i].val; | |||
1331 | ++i) { | |||
1332 | if (long_options[i].val == val) { | |||
1333 | long_options_index = i; | |||
1334 | break; | |||
1335 | } | |||
1336 | } | |||
1337 | } | |||
1338 | // Call the callback with the option | |||
1339 | if (long_options_index >= 0 && | |||
1340 | long_options[long_options_index].definition) { | |||
1341 | const OptionDefinition *def = long_options[long_options_index].definition; | |||
1342 | ||||
1343 | if (!platform_sp) { | |||
1344 | // User did not pass in an explicit platform. Try to grab from the | |||
1345 | // execution context. | |||
1346 | TargetSP target_sp = | |||
1347 | execution_context ? execution_context->GetTargetSP() : TargetSP(); | |||
1348 | platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP(); | |||
1349 | } | |||
1350 | OptionValidator *validator = def->validator; | |||
1351 | ||||
1352 | if (!platform_sp && require_validation) { | |||
1353 | // Caller requires validation but we cannot validate as we don't have | |||
1354 | // the mandatory platform against which to validate. | |||
1355 | return llvm::make_error<llvm::StringError>( | |||
1356 | "cannot validate options: no platform available", | |||
1357 | llvm::inconvertibleErrorCode()); | |||
1358 | } | |||
1359 | ||||
1360 | bool validation_failed = false; | |||
1361 | if (platform_sp) { | |||
1362 | // Ensure we have an execution context, empty or not. | |||
1363 | ExecutionContext dummy_context; | |||
1364 | ExecutionContext *exe_ctx_p = | |||
1365 | execution_context ? execution_context : &dummy_context; | |||
1366 | if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) { | |||
1367 | validation_failed = true; | |||
1368 | error.SetErrorStringWithFormat("Option \"%s\" invalid. %s", | |||
1369 | def->long_option, | |||
1370 | def->validator->LongConditionString()); | |||
1371 | } | |||
1372 | } | |||
1373 | ||||
1374 | // As long as validation didn't fail, we set the option value. | |||
1375 | if (!validation_failed) | |||
1376 | error = | |||
1377 | SetOptionValue(long_options_index, | |||
1378 | (def->option_has_arg == OptionParser::eNoArgument) | |||
1379 | ? nullptr | |||
1380 | : OptionParser::GetOptionArgument(), | |||
1381 | execution_context); | |||
1382 | // If the Option setting returned an error, we should stop parsing | |||
1383 | // and return the error. | |||
1384 | if (error.Fail()) | |||
1385 | break; | |||
1386 | } else { | |||
1387 | error.SetErrorStringWithFormat("invalid option with value '%i'", val); | |||
1388 | } | |||
1389 | } | |||
1390 | ||||
1391 | if (error.Fail()) | |||
1392 | return error.ToError(); | |||
1393 | ||||
1394 | argv.pop_back(); | |||
1395 | argv.erase(argv.begin(), argv.begin() + OptionParser::GetOptionIndex()); | |||
1396 | return ReconstituteArgsAfterParsing(argv, args); | |||
1397 | } |