Handle multiple target events before commit resume
[deliverable/binutils-gdb.git] / gdb / completer.c
1 /* Line completion stuff for GDB, the GNU debugger.
2 Copyright (C) 2000-2020 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18
19 #include "defs.h"
20 #include "symtab.h"
21 #include "gdbtypes.h"
22 #include "expression.h"
23 #include "filenames.h" /* For DOSish file names. */
24 #include "language.h"
25 #include "gdbsupport/gdb_signals.h"
26 #include "target.h"
27 #include "reggroups.h"
28 #include "user-regs.h"
29 #include "arch-utils.h"
30 #include "location.h"
31 #include <algorithm>
32 #include "linespec.h"
33 #include "cli/cli-decode.h"
34
35 /* FIXME: This is needed because of lookup_cmd_1 (). We should be
36 calling a hook instead so we eliminate the CLI dependency. */
37 #include "gdbcmd.h"
38
39 /* Needed for rl_completer_word_break_characters() and for
40 rl_filename_completion_function. */
41 #include "readline/readline.h"
42
43 /* readline defines this. */
44 #undef savestring
45
46 #include "completer.h"
47
48 /* Misc state that needs to be tracked across several different
49 readline completer entry point calls, all related to a single
50 completion invocation. */
51
52 struct gdb_completer_state
53 {
54 /* The current completion's completion tracker. This is a global
55 because a tracker can be shared between the handle_brkchars and
56 handle_completion phases, which involves different readline
57 callbacks. */
58 completion_tracker *tracker = NULL;
59
60 /* Whether the current completion was aborted. */
61 bool aborted = false;
62 };
63
64 /* The current completion state. */
65 static gdb_completer_state current_completion;
66
67 /* An enumeration of the various things a user might attempt to
68 complete for a location. If you change this, remember to update
69 the explicit_options array below too. */
70
71 enum explicit_location_match_type
72 {
73 /* The filename of a source file. */
74 MATCH_SOURCE,
75
76 /* The name of a function or method. */
77 MATCH_FUNCTION,
78
79 /* The fully-qualified name of a function or method. */
80 MATCH_QUALIFIED,
81
82 /* A line number. */
83 MATCH_LINE,
84
85 /* The name of a label. */
86 MATCH_LABEL
87 };
88
89 /* Prototypes for local functions. */
90
91 /* readline uses the word breaks for two things:
92 (1) In figuring out where to point the TEXT parameter to the
93 rl_completion_entry_function. Since we don't use TEXT for much,
94 it doesn't matter a lot what the word breaks are for this purpose,
95 but it does affect how much stuff M-? lists.
96 (2) If one of the matches contains a word break character, readline
97 will quote it. That's why we switch between
98 current_language->la_word_break_characters() and
99 gdb_completer_command_word_break_characters. I'm not sure when
100 we need this behavior (perhaps for funky characters in C++
101 symbols?). */
102
103 /* Variables which are necessary for fancy command line editing. */
104
105 /* When completing on command names, we remove '-' and '.' from the list of
106 word break characters, since we use it in command names. If the
107 readline library sees one in any of the current completion strings,
108 it thinks that the string needs to be quoted and automatically
109 supplies a leading quote. */
110 static const char gdb_completer_command_word_break_characters[] =
111 " \t\n!@#$%^&*()+=|~`}{[]\"';:?/><,";
112
113 /* When completing on file names, we remove from the list of word
114 break characters any characters that are commonly used in file
115 names, such as '-', '+', '~', etc. Otherwise, readline displays
116 incorrect completion candidates. */
117 /* MS-DOS and MS-Windows use colon as part of the drive spec, and most
118 programs support @foo style response files. */
119 static const char gdb_completer_file_name_break_characters[] =
120 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
121 " \t\n*|\"';?><@";
122 #else
123 " \t\n*|\"';:?><";
124 #endif
125
126 /* Characters that can be used to quote completion strings. Note that
127 we can't include '"' because the gdb C parser treats such quoted
128 sequences as strings. */
129 static const char gdb_completer_quote_characters[] = "'";
130 \f
131 /* Accessor for some completer data that may interest other files. */
132
133 const char *
134 get_gdb_completer_quote_characters (void)
135 {
136 return gdb_completer_quote_characters;
137 }
138
139 /* This can be used for functions which don't want to complete on
140 symbols but don't want to complete on anything else either. */
141
142 void
143 noop_completer (struct cmd_list_element *ignore,
144 completion_tracker &tracker,
145 const char *text, const char *prefix)
146 {
147 }
148
149 /* Complete on filenames. */
150
151 void
152 filename_completer (struct cmd_list_element *ignore,
153 completion_tracker &tracker,
154 const char *text, const char *word)
155 {
156 int subsequent_name;
157
158 subsequent_name = 0;
159 while (1)
160 {
161 gdb::unique_xmalloc_ptr<char> p_rl
162 (rl_filename_completion_function (text, subsequent_name));
163 if (p_rl == NULL)
164 break;
165 /* We need to set subsequent_name to a non-zero value before the
166 continue line below, because otherwise, if the first file
167 seen by GDB is a backup file whose name ends in a `~', we
168 will loop indefinitely. */
169 subsequent_name = 1;
170 /* Like emacs, don't complete on old versions. Especially
171 useful in the "source" command. */
172 const char *p = p_rl.get ();
173 if (p[strlen (p) - 1] == '~')
174 continue;
175
176 tracker.add_completion
177 (make_completion_match_str (std::move (p_rl), text, word));
178 }
179 #if 0
180 /* There is no way to do this just long enough to affect quote
181 inserting without also affecting the next completion. This
182 should be fixed in readline. FIXME. */
183 /* Ensure that readline does the right thing
184 with respect to inserting quotes. */
185 rl_completer_word_break_characters = "";
186 #endif
187 }
188
189 /* The corresponding completer_handle_brkchars
190 implementation. */
191
192 static void
193 filename_completer_handle_brkchars (struct cmd_list_element *ignore,
194 completion_tracker &tracker,
195 const char *text, const char *word)
196 {
197 set_rl_completer_word_break_characters
198 (gdb_completer_file_name_break_characters);
199 }
200
201 /* Possible values for the found_quote flags word used by the completion
202 functions. It says what kind of (shell-like) quoting we found anywhere
203 in the line. */
204 #define RL_QF_SINGLE_QUOTE 0x01
205 #define RL_QF_DOUBLE_QUOTE 0x02
206 #define RL_QF_BACKSLASH 0x04
207 #define RL_QF_OTHER_QUOTE 0x08
208
209 /* Find the bounds of the current word for completion purposes, and
210 return a pointer to the end of the word. This mimics (and is a
211 modified version of) readline's _rl_find_completion_word internal
212 function.
213
214 This function skips quoted substrings (characters between matched
215 pairs of characters in rl_completer_quote_characters). We try to
216 find an unclosed quoted substring on which to do matching. If one
217 is not found, we use the word break characters to find the
218 boundaries of the current word. QC, if non-null, is set to the
219 opening quote character if we found an unclosed quoted substring,
220 '\0' otherwise. DP, if non-null, is set to the value of the
221 delimiter character that caused a word break. */
222
223 struct gdb_rl_completion_word_info
224 {
225 const char *word_break_characters;
226 const char *quote_characters;
227 const char *basic_quote_characters;
228 };
229
230 static const char *
231 gdb_rl_find_completion_word (struct gdb_rl_completion_word_info *info,
232 int *qc, int *dp,
233 const char *line_buffer)
234 {
235 int scan, end, found_quote, delimiter, pass_next, isbrk;
236 char quote_char;
237 const char *brkchars;
238 int point = strlen (line_buffer);
239
240 /* The algorithm below does '--point'. Avoid buffer underflow with
241 the empty string. */
242 if (point == 0)
243 {
244 if (qc != NULL)
245 *qc = '\0';
246 if (dp != NULL)
247 *dp = '\0';
248 return line_buffer;
249 }
250
251 end = point;
252 found_quote = delimiter = 0;
253 quote_char = '\0';
254
255 brkchars = info->word_break_characters;
256
257 if (info->quote_characters != NULL)
258 {
259 /* We have a list of characters which can be used in pairs to
260 quote substrings for the completer. Try to find the start of
261 an unclosed quoted substring. */
262 /* FOUND_QUOTE is set so we know what kind of quotes we
263 found. */
264 for (scan = pass_next = 0;
265 scan < end;
266 scan++)
267 {
268 if (pass_next)
269 {
270 pass_next = 0;
271 continue;
272 }
273
274 /* Shell-like semantics for single quotes -- don't allow
275 backslash to quote anything in single quotes, especially
276 not the closing quote. If you don't like this, take out
277 the check on the value of quote_char. */
278 if (quote_char != '\'' && line_buffer[scan] == '\\')
279 {
280 pass_next = 1;
281 found_quote |= RL_QF_BACKSLASH;
282 continue;
283 }
284
285 if (quote_char != '\0')
286 {
287 /* Ignore everything until the matching close quote
288 char. */
289 if (line_buffer[scan] == quote_char)
290 {
291 /* Found matching close. Abandon this
292 substring. */
293 quote_char = '\0';
294 point = end;
295 }
296 }
297 else if (strchr (info->quote_characters, line_buffer[scan]))
298 {
299 /* Found start of a quoted substring. */
300 quote_char = line_buffer[scan];
301 point = scan + 1;
302 /* Shell-like quoting conventions. */
303 if (quote_char == '\'')
304 found_quote |= RL_QF_SINGLE_QUOTE;
305 else if (quote_char == '"')
306 found_quote |= RL_QF_DOUBLE_QUOTE;
307 else
308 found_quote |= RL_QF_OTHER_QUOTE;
309 }
310 }
311 }
312
313 if (point == end && quote_char == '\0')
314 {
315 /* We didn't find an unclosed quoted substring upon which to do
316 completion, so use the word break characters to find the
317 substring on which to complete. */
318 while (--point)
319 {
320 scan = line_buffer[point];
321
322 if (strchr (brkchars, scan) != 0)
323 break;
324 }
325 }
326
327 /* If we are at an unquoted word break, then advance past it. */
328 scan = line_buffer[point];
329
330 if (scan)
331 {
332 isbrk = strchr (brkchars, scan) != 0;
333
334 if (isbrk)
335 {
336 /* If the character that caused the word break was a quoting
337 character, then remember it as the delimiter. */
338 if (info->basic_quote_characters
339 && strchr (info->basic_quote_characters, scan)
340 && (end - point) > 1)
341 delimiter = scan;
342
343 point++;
344 }
345 }
346
347 if (qc != NULL)
348 *qc = quote_char;
349 if (dp != NULL)
350 *dp = delimiter;
351
352 return line_buffer + point;
353 }
354
355 /* Find the completion word point for TEXT, emulating the algorithm
356 readline uses to find the word point, using WORD_BREAK_CHARACTERS
357 as word break characters. */
358
359 static const char *
360 advance_to_completion_word (completion_tracker &tracker,
361 const char *word_break_characters,
362 const char *text)
363 {
364 gdb_rl_completion_word_info info;
365
366 info.word_break_characters = word_break_characters;
367 info.quote_characters = gdb_completer_quote_characters;
368 info.basic_quote_characters = rl_basic_quote_characters;
369
370 int delimiter;
371 const char *start
372 = gdb_rl_find_completion_word (&info, NULL, &delimiter, text);
373
374 tracker.advance_custom_word_point_by (start - text);
375
376 if (delimiter)
377 {
378 tracker.set_quote_char (delimiter);
379 tracker.set_suppress_append_ws (true);
380 }
381
382 return start;
383 }
384
385 /* See completer.h. */
386
387 const char *
388 advance_to_expression_complete_word_point (completion_tracker &tracker,
389 const char *text)
390 {
391 const char *brk_chars = current_language->la_word_break_characters ();
392 return advance_to_completion_word (tracker, brk_chars, text);
393 }
394
395 /* See completer.h. */
396
397 const char *
398 advance_to_filename_complete_word_point (completion_tracker &tracker,
399 const char *text)
400 {
401 const char *brk_chars = gdb_completer_file_name_break_characters;
402 return advance_to_completion_word (tracker, brk_chars, text);
403 }
404
405 /* See completer.h. */
406
407 bool
408 completion_tracker::completes_to_completion_word (const char *word)
409 {
410 if (m_lowest_common_denominator_unique)
411 {
412 const char *lcd = m_lowest_common_denominator;
413
414 if (strncmp_iw (word, lcd, strlen (lcd)) == 0)
415 {
416 /* Maybe skip the function and complete on keywords. */
417 size_t wordlen = strlen (word);
418 if (word[wordlen - 1] == ' ')
419 return true;
420 }
421 }
422
423 return false;
424 }
425
426 /* See completer.h. */
427
428 void
429 complete_nested_command_line (completion_tracker &tracker, const char *text)
430 {
431 /* Must be called from a custom-word-point completer. */
432 gdb_assert (tracker.use_custom_word_point ());
433
434 /* Disable the custom word point temporarily, because we want to
435 probe whether the command we're completing itself uses a custom
436 word point. */
437 tracker.set_use_custom_word_point (false);
438 size_t save_custom_word_point = tracker.custom_word_point ();
439
440 int quote_char = '\0';
441 const char *word = completion_find_completion_word (tracker, text,
442 &quote_char);
443
444 if (tracker.use_custom_word_point ())
445 {
446 /* The command we're completing uses a custom word point, so the
447 tracker already contains the matches. We're done. */
448 return;
449 }
450
451 /* Restore the custom word point settings. */
452 tracker.set_custom_word_point (save_custom_word_point);
453 tracker.set_use_custom_word_point (true);
454
455 /* Run the handle_completions completer phase. */
456 complete_line (tracker, word, text, strlen (text));
457 }
458
459 /* Complete on linespecs, which might be of two possible forms:
460
461 file:line
462 or
463 symbol+offset
464
465 This is intended to be used in commands that set breakpoints
466 etc. */
467
468 static void
469 complete_files_symbols (completion_tracker &tracker,
470 const char *text, const char *word)
471 {
472 completion_list fn_list;
473 const char *p;
474 int quote_found = 0;
475 int quoted = *text == '\'' || *text == '"';
476 int quote_char = '\0';
477 const char *colon = NULL;
478 char *file_to_match = NULL;
479 const char *symbol_start = text;
480 const char *orig_text = text;
481
482 /* Do we have an unquoted colon, as in "break foo.c:bar"? */
483 for (p = text; *p != '\0'; ++p)
484 {
485 if (*p == '\\' && p[1] == '\'')
486 p++;
487 else if (*p == '\'' || *p == '"')
488 {
489 quote_found = *p;
490 quote_char = *p++;
491 while (*p != '\0' && *p != quote_found)
492 {
493 if (*p == '\\' && p[1] == quote_found)
494 p++;
495 p++;
496 }
497
498 if (*p == quote_found)
499 quote_found = 0;
500 else
501 break; /* Hit the end of text. */
502 }
503 #if HAVE_DOS_BASED_FILE_SYSTEM
504 /* If we have a DOS-style absolute file name at the beginning of
505 TEXT, and the colon after the drive letter is the only colon
506 we found, pretend the colon is not there. */
507 else if (p < text + 3 && *p == ':' && p == text + 1 + quoted)
508 ;
509 #endif
510 else if (*p == ':' && !colon)
511 {
512 colon = p;
513 symbol_start = p + 1;
514 }
515 else if (strchr (current_language->la_word_break_characters(), *p))
516 symbol_start = p + 1;
517 }
518
519 if (quoted)
520 text++;
521
522 /* Where is the file name? */
523 if (colon)
524 {
525 char *s;
526
527 file_to_match = (char *) xmalloc (colon - text + 1);
528 strncpy (file_to_match, text, colon - text);
529 file_to_match[colon - text] = '\0';
530 /* Remove trailing colons and quotes from the file name. */
531 for (s = file_to_match + (colon - text);
532 s > file_to_match;
533 s--)
534 if (*s == ':' || *s == quote_char)
535 *s = '\0';
536 }
537 /* If the text includes a colon, they want completion only on a
538 symbol name after the colon. Otherwise, we need to complete on
539 symbols as well as on files. */
540 if (colon)
541 {
542 collect_file_symbol_completion_matches (tracker,
543 complete_symbol_mode::EXPRESSION,
544 symbol_name_match_type::EXPRESSION,
545 symbol_start, word,
546 file_to_match);
547 xfree (file_to_match);
548 }
549 else
550 {
551 size_t text_len = strlen (text);
552
553 collect_symbol_completion_matches (tracker,
554 complete_symbol_mode::EXPRESSION,
555 symbol_name_match_type::EXPRESSION,
556 symbol_start, word);
557 /* If text includes characters which cannot appear in a file
558 name, they cannot be asking for completion on files. */
559 if (strcspn (text,
560 gdb_completer_file_name_break_characters) == text_len)
561 fn_list = make_source_files_completion_list (text, text);
562 }
563
564 if (!fn_list.empty () && !tracker.have_completions ())
565 {
566 /* If we only have file names as possible completion, we should
567 bring them in sync with what rl_complete expects. The
568 problem is that if the user types "break /foo/b TAB", and the
569 possible completions are "/foo/bar" and "/foo/baz"
570 rl_complete expects us to return "bar" and "baz", without the
571 leading directories, as possible completions, because `word'
572 starts at the "b". But we ignore the value of `word' when we
573 call make_source_files_completion_list above (because that
574 would not DTRT when the completion results in both symbols
575 and file names), so make_source_files_completion_list returns
576 the full "/foo/bar" and "/foo/baz" strings. This produces
577 wrong results when, e.g., there's only one possible
578 completion, because rl_complete will prepend "/foo/" to each
579 candidate completion. The loop below removes that leading
580 part. */
581 for (const auto &fn_up: fn_list)
582 {
583 char *fn = fn_up.get ();
584 memmove (fn, fn + (word - text), strlen (fn) + 1 - (word - text));
585 }
586 }
587
588 tracker.add_completions (std::move (fn_list));
589
590 if (!tracker.have_completions ())
591 {
592 /* No completions at all. As the final resort, try completing
593 on the entire text as a symbol. */
594 collect_symbol_completion_matches (tracker,
595 complete_symbol_mode::EXPRESSION,
596 symbol_name_match_type::EXPRESSION,
597 orig_text, word);
598 }
599 }
600
601 /* See completer.h. */
602
603 completion_list
604 complete_source_filenames (const char *text)
605 {
606 size_t text_len = strlen (text);
607
608 /* If text includes characters which cannot appear in a file name,
609 the user cannot be asking for completion on files. */
610 if (strcspn (text,
611 gdb_completer_file_name_break_characters)
612 == text_len)
613 return make_source_files_completion_list (text, text);
614
615 return {};
616 }
617
618 /* Complete address and linespec locations. */
619
620 static void
621 complete_address_and_linespec_locations (completion_tracker &tracker,
622 const char *text,
623 symbol_name_match_type match_type)
624 {
625 if (*text == '*')
626 {
627 tracker.advance_custom_word_point_by (1);
628 text++;
629 const char *word
630 = advance_to_expression_complete_word_point (tracker, text);
631 complete_expression (tracker, text, word);
632 }
633 else
634 {
635 linespec_complete (tracker, text, match_type);
636 }
637 }
638
639 /* The explicit location options. Note that indexes into this array
640 must match the explicit_location_match_type enumerators. */
641
642 static const char *const explicit_options[] =
643 {
644 "-source",
645 "-function",
646 "-qualified",
647 "-line",
648 "-label",
649 NULL
650 };
651
652 /* The probe modifier options. These can appear before a location in
653 breakpoint commands. */
654 static const char *const probe_options[] =
655 {
656 "-probe",
657 "-probe-stap",
658 "-probe-dtrace",
659 NULL
660 };
661
662 /* Returns STRING if not NULL, the empty string otherwise. */
663
664 static const char *
665 string_or_empty (const char *string)
666 {
667 return string != NULL ? string : "";
668 }
669
670 /* A helper function to collect explicit location matches for the given
671 LOCATION, which is attempting to match on WORD. */
672
673 static void
674 collect_explicit_location_matches (completion_tracker &tracker,
675 struct event_location *location,
676 enum explicit_location_match_type what,
677 const char *word,
678 const struct language_defn *language)
679 {
680 const struct explicit_location *explicit_loc
681 = get_explicit_location (location);
682
683 /* True if the option expects an argument. */
684 bool needs_arg = true;
685
686 /* Note, in the various MATCH_* below, we complete on
687 explicit_loc->foo instead of WORD, because only the former will
688 have already skipped past any quote char. */
689 switch (what)
690 {
691 case MATCH_SOURCE:
692 {
693 const char *source = string_or_empty (explicit_loc->source_filename);
694 completion_list matches
695 = make_source_files_completion_list (source, source);
696 tracker.add_completions (std::move (matches));
697 }
698 break;
699
700 case MATCH_FUNCTION:
701 {
702 const char *function = string_or_empty (explicit_loc->function_name);
703 linespec_complete_function (tracker, function,
704 explicit_loc->func_name_match_type,
705 explicit_loc->source_filename);
706 }
707 break;
708
709 case MATCH_QUALIFIED:
710 needs_arg = false;
711 break;
712 case MATCH_LINE:
713 /* Nothing to offer. */
714 break;
715
716 case MATCH_LABEL:
717 {
718 const char *label = string_or_empty (explicit_loc->label_name);
719 linespec_complete_label (tracker, language,
720 explicit_loc->source_filename,
721 explicit_loc->function_name,
722 explicit_loc->func_name_match_type,
723 label);
724 }
725 break;
726
727 default:
728 gdb_assert_not_reached ("unhandled explicit_location_match_type");
729 }
730
731 if (!needs_arg || tracker.completes_to_completion_word (word))
732 {
733 tracker.discard_completions ();
734 tracker.advance_custom_word_point_by (strlen (word));
735 complete_on_enum (tracker, explicit_options, "", "");
736 complete_on_enum (tracker, linespec_keywords, "", "");
737 }
738 else if (!tracker.have_completions ())
739 {
740 /* Maybe we have an unterminated linespec keyword at the tail of
741 the string. Try completing on that. */
742 size_t wordlen = strlen (word);
743 const char *keyword = word + wordlen;
744
745 if (wordlen > 0 && keyword[-1] != ' ')
746 {
747 while (keyword > word && *keyword != ' ')
748 keyword--;
749 /* Don't complete on keywords if we'd be completing on the
750 whole explicit linespec option. E.g., "b -function
751 thr<tab>" should not complete to the "thread"
752 keyword. */
753 if (keyword != word)
754 {
755 keyword = skip_spaces (keyword);
756
757 tracker.advance_custom_word_point_by (keyword - word);
758 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
759 }
760 }
761 else if (wordlen > 0 && keyword[-1] == ' ')
762 {
763 /* Assume that we're maybe past the explicit location
764 argument, and we didn't manage to find any match because
765 the user wants to create a pending breakpoint. Offer the
766 keyword and explicit location options as possible
767 completions. */
768 tracker.advance_custom_word_point_by (keyword - word);
769 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
770 complete_on_enum (tracker, explicit_options, keyword, keyword);
771 }
772 }
773 }
774
775 /* If the next word in *TEXT_P is any of the keywords in KEYWORDS,
776 then advance both TEXT_P and the word point in the tracker past the
777 keyword and return the (0-based) index in the KEYWORDS array that
778 matched. Otherwise, return -1. */
779
780 static int
781 skip_keyword (completion_tracker &tracker,
782 const char * const *keywords, const char **text_p)
783 {
784 const char *text = *text_p;
785 const char *after = skip_to_space (text);
786 size_t len = after - text;
787
788 if (text[len] != ' ')
789 return -1;
790
791 int found = -1;
792 for (int i = 0; keywords[i] != NULL; i++)
793 {
794 if (strncmp (keywords[i], text, len) == 0)
795 {
796 if (found == -1)
797 found = i;
798 else
799 return -1;
800 }
801 }
802
803 if (found != -1)
804 {
805 tracker.advance_custom_word_point_by (len + 1);
806 text += len + 1;
807 *text_p = text;
808 return found;
809 }
810
811 return -1;
812 }
813
814 /* A completer function for explicit locations. This function
815 completes both options ("-source", "-line", etc) and values. If
816 completing a quoted string, then QUOTED_ARG_START and
817 QUOTED_ARG_END point to the quote characters. LANGUAGE is the
818 current language. */
819
820 static void
821 complete_explicit_location (completion_tracker &tracker,
822 struct event_location *location,
823 const char *text,
824 const language_defn *language,
825 const char *quoted_arg_start,
826 const char *quoted_arg_end)
827 {
828 if (*text != '-')
829 return;
830
831 int keyword = skip_keyword (tracker, explicit_options, &text);
832
833 if (keyword == -1)
834 complete_on_enum (tracker, explicit_options, text, text);
835 else
836 {
837 /* Completing on value. */
838 enum explicit_location_match_type what
839 = (explicit_location_match_type) keyword;
840
841 if (quoted_arg_start != NULL && quoted_arg_end != NULL)
842 {
843 if (quoted_arg_end[1] == '\0')
844 {
845 /* If completing a quoted string with the cursor right
846 at the terminating quote char, complete the
847 completion word without interpretation, so that
848 readline advances the cursor one whitespace past the
849 quote, even if there's no match. This makes these
850 cases behave the same:
851
852 before: "b -function function()"
853 after: "b -function function() "
854
855 before: "b -function 'function()'"
856 after: "b -function 'function()' "
857
858 and trusts the user in this case:
859
860 before: "b -function 'not_loaded_function_yet()'"
861 after: "b -function 'not_loaded_function_yet()' "
862 */
863 tracker.add_completion (make_unique_xstrdup (text));
864 }
865 else if (quoted_arg_end[1] == ' ')
866 {
867 /* We're maybe past the explicit location argument.
868 Skip the argument without interpretation, assuming the
869 user may want to create pending breakpoint. Offer
870 the keyword and explicit location options as possible
871 completions. */
872 tracker.advance_custom_word_point_by (strlen (text));
873 complete_on_enum (tracker, linespec_keywords, "", "");
874 complete_on_enum (tracker, explicit_options, "", "");
875 }
876 return;
877 }
878
879 /* Now gather matches */
880 collect_explicit_location_matches (tracker, location, what, text,
881 language);
882 }
883 }
884
885 /* A completer for locations. */
886
887 void
888 location_completer (struct cmd_list_element *ignore,
889 completion_tracker &tracker,
890 const char *text, const char * /* word */)
891 {
892 int found_probe_option = -1;
893
894 /* If we have a probe modifier, skip it. This can only appear as
895 first argument. Until we have a specific completer for probes,
896 falling back to the linespec completer for the remainder of the
897 line is better than nothing. */
898 if (text[0] == '-' && text[1] == 'p')
899 found_probe_option = skip_keyword (tracker, probe_options, &text);
900
901 const char *option_text = text;
902 int saved_word_point = tracker.custom_word_point ();
903
904 const char *copy = text;
905
906 explicit_completion_info completion_info;
907 event_location_up location
908 = string_to_explicit_location (&copy, current_language,
909 &completion_info);
910 if (completion_info.quoted_arg_start != NULL
911 && completion_info.quoted_arg_end == NULL)
912 {
913 /* Found an unbalanced quote. */
914 tracker.set_quote_char (*completion_info.quoted_arg_start);
915 tracker.advance_custom_word_point_by (1);
916 }
917
918 if (completion_info.saw_explicit_location_option)
919 {
920 if (*copy != '\0')
921 {
922 tracker.advance_custom_word_point_by (copy - text);
923 text = copy;
924
925 /* We found a terminator at the tail end of the string,
926 which means we're past the explicit location options. We
927 may have a keyword to complete on. If we have a whole
928 keyword, then complete whatever comes after as an
929 expression. This is mainly for the "if" keyword. If the
930 "thread" and "task" keywords gain their own completers,
931 they should be used here. */
932 int keyword = skip_keyword (tracker, linespec_keywords, &text);
933
934 if (keyword == -1)
935 {
936 complete_on_enum (tracker, linespec_keywords, text, text);
937 }
938 else
939 {
940 const char *word
941 = advance_to_expression_complete_word_point (tracker, text);
942 complete_expression (tracker, text, word);
943 }
944 }
945 else
946 {
947 tracker.advance_custom_word_point_by (completion_info.last_option
948 - text);
949 text = completion_info.last_option;
950
951 complete_explicit_location (tracker, location.get (), text,
952 current_language,
953 completion_info.quoted_arg_start,
954 completion_info.quoted_arg_end);
955
956 }
957 }
958 /* This is an address or linespec location. */
959 else if (location != NULL)
960 {
961 /* Handle non-explicit location options. */
962
963 int keyword = skip_keyword (tracker, explicit_options, &text);
964 if (keyword == -1)
965 complete_on_enum (tracker, explicit_options, text, text);
966 else
967 {
968 tracker.advance_custom_word_point_by (copy - text);
969 text = copy;
970
971 symbol_name_match_type match_type
972 = get_explicit_location (location.get ())->func_name_match_type;
973 complete_address_and_linespec_locations (tracker, text, match_type);
974 }
975 }
976 else
977 {
978 /* No options. */
979 complete_address_and_linespec_locations (tracker, text,
980 symbol_name_match_type::WILD);
981 }
982
983 /* Add matches for option names, if either:
984
985 - Some completer above found some matches, but the word point did
986 not advance (e.g., "b <tab>" finds all functions, or "b -<tab>"
987 matches all objc selectors), or;
988
989 - Some completer above advanced the word point, but found no
990 matches.
991 */
992 if ((text[0] == '-' || text[0] == '\0')
993 && (!tracker.have_completions ()
994 || tracker.custom_word_point () == saved_word_point))
995 {
996 tracker.set_custom_word_point (saved_word_point);
997 text = option_text;
998
999 if (found_probe_option == -1)
1000 complete_on_enum (tracker, probe_options, text, text);
1001 complete_on_enum (tracker, explicit_options, text, text);
1002 }
1003 }
1004
1005 /* The corresponding completer_handle_brkchars
1006 implementation. */
1007
1008 static void
1009 location_completer_handle_brkchars (struct cmd_list_element *ignore,
1010 completion_tracker &tracker,
1011 const char *text,
1012 const char *word_ignored)
1013 {
1014 tracker.set_use_custom_word_point (true);
1015
1016 location_completer (ignore, tracker, text, NULL);
1017 }
1018
1019 /* Helper for expression_completer which recursively adds field and
1020 method names from TYPE, a struct or union type, to the OUTPUT
1021 list. */
1022
1023 static void
1024 add_struct_fields (struct type *type, completion_list &output,
1025 const char *fieldname, int namelen)
1026 {
1027 int i;
1028 int computed_type_name = 0;
1029 const char *type_name = NULL;
1030
1031 type = check_typedef (type);
1032 for (i = 0; i < TYPE_NFIELDS (type); ++i)
1033 {
1034 if (i < TYPE_N_BASECLASSES (type))
1035 add_struct_fields (TYPE_BASECLASS (type, i),
1036 output, fieldname, namelen);
1037 else if (TYPE_FIELD_NAME (type, i))
1038 {
1039 if (TYPE_FIELD_NAME (type, i)[0] != '\0')
1040 {
1041 if (! strncmp (TYPE_FIELD_NAME (type, i),
1042 fieldname, namelen))
1043 output.emplace_back (xstrdup (TYPE_FIELD_NAME (type, i)));
1044 }
1045 else if (TYPE_CODE (TYPE_FIELD_TYPE (type, i)) == TYPE_CODE_UNION)
1046 {
1047 /* Recurse into anonymous unions. */
1048 add_struct_fields (TYPE_FIELD_TYPE (type, i),
1049 output, fieldname, namelen);
1050 }
1051 }
1052 }
1053
1054 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; --i)
1055 {
1056 const char *name = TYPE_FN_FIELDLIST_NAME (type, i);
1057
1058 if (name && ! strncmp (name, fieldname, namelen))
1059 {
1060 if (!computed_type_name)
1061 {
1062 type_name = TYPE_NAME (type);
1063 computed_type_name = 1;
1064 }
1065 /* Omit constructors from the completion list. */
1066 if (!type_name || strcmp (type_name, name))
1067 output.emplace_back (xstrdup (name));
1068 }
1069 }
1070 }
1071
1072 /* See completer.h. */
1073
1074 void
1075 complete_expression (completion_tracker &tracker,
1076 const char *text, const char *word)
1077 {
1078 struct type *type = NULL;
1079 gdb::unique_xmalloc_ptr<char> fieldname;
1080 enum type_code code = TYPE_CODE_UNDEF;
1081
1082 /* Perform a tentative parse of the expression, to see whether a
1083 field completion is required. */
1084 try
1085 {
1086 type = parse_expression_for_completion (text, &fieldname, &code);
1087 }
1088 catch (const gdb_exception_error &except)
1089 {
1090 return;
1091 }
1092
1093 if (fieldname != nullptr && type)
1094 {
1095 for (;;)
1096 {
1097 type = check_typedef (type);
1098 if (TYPE_CODE (type) != TYPE_CODE_PTR && !TYPE_IS_REFERENCE (type))
1099 break;
1100 type = TYPE_TARGET_TYPE (type);
1101 }
1102
1103 if (TYPE_CODE (type) == TYPE_CODE_UNION
1104 || TYPE_CODE (type) == TYPE_CODE_STRUCT)
1105 {
1106 completion_list result;
1107
1108 add_struct_fields (type, result, fieldname.get (),
1109 strlen (fieldname.get ()));
1110 tracker.add_completions (std::move (result));
1111 return;
1112 }
1113 }
1114 else if (fieldname != nullptr && code != TYPE_CODE_UNDEF)
1115 {
1116 collect_symbol_completion_matches_type (tracker, fieldname.get (),
1117 fieldname.get (), code);
1118 return;
1119 }
1120
1121 complete_files_symbols (tracker, text, word);
1122 }
1123
1124 /* Complete on expressions. Often this means completing on symbol
1125 names, but some language parsers also have support for completing
1126 field names. */
1127
1128 void
1129 expression_completer (struct cmd_list_element *ignore,
1130 completion_tracker &tracker,
1131 const char *text, const char *word)
1132 {
1133 complete_expression (tracker, text, word);
1134 }
1135
1136 /* See definition in completer.h. */
1137
1138 void
1139 set_rl_completer_word_break_characters (const char *break_chars)
1140 {
1141 rl_completer_word_break_characters = (char *) break_chars;
1142 }
1143
1144 /* Complete on symbols. */
1145
1146 void
1147 symbol_completer (struct cmd_list_element *ignore,
1148 completion_tracker &tracker,
1149 const char *text, const char *word)
1150 {
1151 collect_symbol_completion_matches (tracker, complete_symbol_mode::EXPRESSION,
1152 symbol_name_match_type::EXPRESSION,
1153 text, word);
1154 }
1155
1156 /* Here are some useful test cases for completion. FIXME: These
1157 should be put in the test suite. They should be tested with both
1158 M-? and TAB.
1159
1160 "show output-" "radix"
1161 "show output" "-radix"
1162 "p" ambiguous (commands starting with p--path, print, printf, etc.)
1163 "p " ambiguous (all symbols)
1164 "info t foo" no completions
1165 "info t " no completions
1166 "info t" ambiguous ("info target", "info terminal", etc.)
1167 "info ajksdlfk" no completions
1168 "info ajksdlfk " no completions
1169 "info" " "
1170 "info " ambiguous (all info commands)
1171 "p \"a" no completions (string constant)
1172 "p 'a" ambiguous (all symbols starting with a)
1173 "p b-a" ambiguous (all symbols starting with a)
1174 "p b-" ambiguous (all symbols)
1175 "file Make" "file" (word break hard to screw up here)
1176 "file ../gdb.stabs/we" "ird" (needs to not break word at slash)
1177 */
1178
1179 enum complete_line_internal_reason
1180 {
1181 /* Preliminary phase, called by gdb_completion_word_break_characters
1182 function, is used to either:
1183
1184 #1 - Determine the set of chars that are word delimiters
1185 depending on the current command in line_buffer.
1186
1187 #2 - Manually advance RL_POINT to the "word break" point instead
1188 of letting readline do it (based on too-simple character
1189 matching).
1190
1191 Simpler completers that just pass a brkchars array to readline
1192 (#1 above) must defer generating the completions to the main
1193 phase (below). No completion list should be generated in this
1194 phase.
1195
1196 OTOH, completers that manually advance the word point(#2 above)
1197 must set "use_custom_word_point" in the tracker and generate
1198 their completion in this phase. Note that this is the convenient
1199 thing to do since they'll be parsing the input line anyway. */
1200 handle_brkchars,
1201
1202 /* Main phase, called by complete_line function, is used to get the
1203 list of possible completions. */
1204 handle_completions,
1205
1206 /* Special case when completing a 'help' command. In this case,
1207 once sub-command completions are exhausted, we simply return
1208 NULL. */
1209 handle_help,
1210 };
1211
1212 /* Helper for complete_line_internal to simplify it. */
1213
1214 static void
1215 complete_line_internal_normal_command (completion_tracker &tracker,
1216 const char *command, const char *word,
1217 const char *cmd_args,
1218 complete_line_internal_reason reason,
1219 struct cmd_list_element *c)
1220 {
1221 const char *p = cmd_args;
1222
1223 if (c->completer == filename_completer)
1224 {
1225 /* Many commands which want to complete on file names accept
1226 several file names, as in "run foo bar >>baz". So we don't
1227 want to complete the entire text after the command, just the
1228 last word. To this end, we need to find the beginning of the
1229 file name by starting at `word' and going backwards. */
1230 for (p = word;
1231 p > command
1232 && strchr (gdb_completer_file_name_break_characters,
1233 p[-1]) == NULL;
1234 p--)
1235 ;
1236 }
1237
1238 if (reason == handle_brkchars)
1239 {
1240 completer_handle_brkchars_ftype *brkchars_fn;
1241
1242 if (c->completer_handle_brkchars != NULL)
1243 brkchars_fn = c->completer_handle_brkchars;
1244 else
1245 {
1246 brkchars_fn
1247 = (completer_handle_brkchars_func_for_completer
1248 (c->completer));
1249 }
1250
1251 brkchars_fn (c, tracker, p, word);
1252 }
1253
1254 if (reason != handle_brkchars && c->completer != NULL)
1255 (*c->completer) (c, tracker, p, word);
1256 }
1257
1258 /* Internal function used to handle completions.
1259
1260
1261 TEXT is the caller's idea of the "word" we are looking at.
1262
1263 LINE_BUFFER is available to be looked at; it contains the entire
1264 text of the line. POINT is the offset in that line of the cursor.
1265 You should pretend that the line ends at POINT.
1266
1267 See complete_line_internal_reason for description of REASON. */
1268
1269 static void
1270 complete_line_internal_1 (completion_tracker &tracker,
1271 const char *text,
1272 const char *line_buffer, int point,
1273 complete_line_internal_reason reason)
1274 {
1275 char *tmp_command;
1276 const char *p;
1277 int ignore_help_classes;
1278 /* Pointer within tmp_command which corresponds to text. */
1279 const char *word;
1280 struct cmd_list_element *c, *result_list;
1281
1282 /* Choose the default set of word break characters to break
1283 completions. If we later find out that we are doing completions
1284 on command strings (as opposed to strings supplied by the
1285 individual command completer functions, which can be any string)
1286 then we will switch to the special word break set for command
1287 strings, which leaves out the '-' and '.' character used in some
1288 commands. */
1289 set_rl_completer_word_break_characters
1290 (current_language->la_word_break_characters());
1291
1292 /* Decide whether to complete on a list of gdb commands or on
1293 symbols. */
1294 tmp_command = (char *) alloca (point + 1);
1295 p = tmp_command;
1296
1297 /* The help command should complete help aliases. */
1298 ignore_help_classes = reason != handle_help;
1299
1300 strncpy (tmp_command, line_buffer, point);
1301 tmp_command[point] = '\0';
1302 if (reason == handle_brkchars)
1303 {
1304 gdb_assert (text == NULL);
1305 word = NULL;
1306 }
1307 else
1308 {
1309 /* Since text always contains some number of characters leading up
1310 to point, we can find the equivalent position in tmp_command
1311 by subtracting that many characters from the end of tmp_command. */
1312 word = tmp_command + point - strlen (text);
1313 }
1314
1315 /* Move P up to the start of the command. */
1316 p = skip_spaces (p);
1317
1318 if (*p == '\0')
1319 {
1320 /* An empty line is ambiguous; that is, it could be any
1321 command. */
1322 c = CMD_LIST_AMBIGUOUS;
1323 result_list = 0;
1324 }
1325 else
1326 {
1327 c = lookup_cmd_1 (&p, cmdlist, &result_list, ignore_help_classes);
1328 }
1329
1330 /* Move p up to the next interesting thing. */
1331 while (*p == ' ' || *p == '\t')
1332 {
1333 p++;
1334 }
1335
1336 tracker.advance_custom_word_point_by (p - tmp_command);
1337
1338 if (!c)
1339 {
1340 /* It is an unrecognized command. So there are no
1341 possible completions. */
1342 }
1343 else if (c == CMD_LIST_AMBIGUOUS)
1344 {
1345 const char *q;
1346
1347 /* lookup_cmd_1 advances p up to the first ambiguous thing, but
1348 doesn't advance over that thing itself. Do so now. */
1349 q = p;
1350 while (valid_cmd_char_p (*q))
1351 ++q;
1352 if (q != tmp_command + point)
1353 {
1354 /* There is something beyond the ambiguous
1355 command, so there are no possible completions. For
1356 example, "info t " or "info t foo" does not complete
1357 to anything, because "info t" can be "info target" or
1358 "info terminal". */
1359 }
1360 else
1361 {
1362 /* We're trying to complete on the command which was ambiguous.
1363 This we can deal with. */
1364 if (result_list)
1365 {
1366 if (reason != handle_brkchars)
1367 complete_on_cmdlist (*result_list->prefixlist, tracker, p,
1368 word, ignore_help_classes);
1369 }
1370 else
1371 {
1372 if (reason != handle_brkchars)
1373 complete_on_cmdlist (cmdlist, tracker, p, word,
1374 ignore_help_classes);
1375 }
1376 /* Ensure that readline does the right thing with respect to
1377 inserting quotes. */
1378 set_rl_completer_word_break_characters
1379 (gdb_completer_command_word_break_characters);
1380 }
1381 }
1382 else
1383 {
1384 /* We've recognized a full command. */
1385
1386 if (p == tmp_command + point)
1387 {
1388 /* There is no non-whitespace in the line beyond the
1389 command. */
1390
1391 if (p[-1] == ' ' || p[-1] == '\t')
1392 {
1393 /* The command is followed by whitespace; we need to
1394 complete on whatever comes after command. */
1395 if (c->prefixlist)
1396 {
1397 /* It is a prefix command; what comes after it is
1398 a subcommand (e.g. "info "). */
1399 if (reason != handle_brkchars)
1400 complete_on_cmdlist (*c->prefixlist, tracker, p, word,
1401 ignore_help_classes);
1402
1403 /* Ensure that readline does the right thing
1404 with respect to inserting quotes. */
1405 set_rl_completer_word_break_characters
1406 (gdb_completer_command_word_break_characters);
1407 }
1408 else if (reason == handle_help)
1409 ;
1410 else if (c->enums)
1411 {
1412 if (reason != handle_brkchars)
1413 complete_on_enum (tracker, c->enums, p, word);
1414 set_rl_completer_word_break_characters
1415 (gdb_completer_command_word_break_characters);
1416 }
1417 else
1418 {
1419 /* It is a normal command; what comes after it is
1420 completed by the command's completer function. */
1421 complete_line_internal_normal_command (tracker,
1422 tmp_command, word, p,
1423 reason, c);
1424 }
1425 }
1426 else
1427 {
1428 /* The command is not followed by whitespace; we need to
1429 complete on the command itself, e.g. "p" which is a
1430 command itself but also can complete to "print", "ptype"
1431 etc. */
1432 const char *q;
1433
1434 /* Find the command we are completing on. */
1435 q = p;
1436 while (q > tmp_command)
1437 {
1438 if (valid_cmd_char_p (q[-1]))
1439 --q;
1440 else
1441 break;
1442 }
1443
1444 /* Move the custom word point back too. */
1445 tracker.advance_custom_word_point_by (q - p);
1446
1447 if (reason != handle_brkchars)
1448 complete_on_cmdlist (result_list, tracker, q, word,
1449 ignore_help_classes);
1450
1451 /* Ensure that readline does the right thing
1452 with respect to inserting quotes. */
1453 set_rl_completer_word_break_characters
1454 (gdb_completer_command_word_break_characters);
1455 }
1456 }
1457 else if (reason == handle_help)
1458 ;
1459 else
1460 {
1461 /* There is non-whitespace beyond the command. */
1462
1463 if (c->prefixlist && !c->allow_unknown)
1464 {
1465 /* It is an unrecognized subcommand of a prefix command,
1466 e.g. "info adsfkdj". */
1467 }
1468 else if (c->enums)
1469 {
1470 if (reason != handle_brkchars)
1471 complete_on_enum (tracker, c->enums, p, word);
1472 }
1473 else
1474 {
1475 /* It is a normal command. */
1476 complete_line_internal_normal_command (tracker,
1477 tmp_command, word, p,
1478 reason, c);
1479 }
1480 }
1481 }
1482 }
1483
1484 /* Wrapper around complete_line_internal_1 to handle
1485 MAX_COMPLETIONS_REACHED_ERROR. */
1486
1487 static void
1488 complete_line_internal (completion_tracker &tracker,
1489 const char *text,
1490 const char *line_buffer, int point,
1491 complete_line_internal_reason reason)
1492 {
1493 try
1494 {
1495 complete_line_internal_1 (tracker, text, line_buffer, point, reason);
1496 }
1497 catch (const gdb_exception_error &except)
1498 {
1499 if (except.error != MAX_COMPLETIONS_REACHED_ERROR)
1500 throw;
1501 }
1502 }
1503
1504 /* See completer.h. */
1505
1506 int max_completions = 200;
1507
1508 /* Initial size of the table. It automagically grows from here. */
1509 #define INITIAL_COMPLETION_HTAB_SIZE 200
1510
1511 /* See completer.h. */
1512
1513 completion_tracker::completion_tracker ()
1514 {
1515 m_entries_hash = htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
1516 htab_hash_string, streq_hash,
1517 NULL, xcalloc, xfree);
1518 }
1519
1520 /* See completer.h. */
1521
1522 void
1523 completion_tracker::discard_completions ()
1524 {
1525 xfree (m_lowest_common_denominator);
1526 m_lowest_common_denominator = NULL;
1527
1528 m_lowest_common_denominator_unique = false;
1529
1530 m_entries_vec.clear ();
1531
1532 htab_delete (m_entries_hash);
1533 m_entries_hash = htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
1534 htab_hash_string, streq_hash,
1535 NULL, xcalloc, xfree);
1536 }
1537
1538 /* See completer.h. */
1539
1540 completion_tracker::~completion_tracker ()
1541 {
1542 xfree (m_lowest_common_denominator);
1543 htab_delete (m_entries_hash);
1544 }
1545
1546 /* See completer.h. */
1547
1548 bool
1549 completion_tracker::maybe_add_completion
1550 (gdb::unique_xmalloc_ptr<char> name,
1551 completion_match_for_lcd *match_for_lcd,
1552 const char *text, const char *word)
1553 {
1554 void **slot;
1555
1556 if (max_completions == 0)
1557 return false;
1558
1559 if (htab_elements (m_entries_hash) >= max_completions)
1560 return false;
1561
1562 slot = htab_find_slot (m_entries_hash, name.get (), INSERT);
1563 if (*slot == HTAB_EMPTY_ENTRY)
1564 {
1565 const char *match_for_lcd_str = NULL;
1566
1567 if (match_for_lcd != NULL)
1568 match_for_lcd_str = match_for_lcd->finish ();
1569
1570 if (match_for_lcd_str == NULL)
1571 match_for_lcd_str = name.get ();
1572
1573 gdb::unique_xmalloc_ptr<char> lcd
1574 = make_completion_match_str (match_for_lcd_str, text, word);
1575
1576 recompute_lowest_common_denominator (std::move (lcd));
1577
1578 *slot = name.get ();
1579 m_entries_vec.push_back (std::move (name));
1580 }
1581
1582 return true;
1583 }
1584
1585 /* See completer.h. */
1586
1587 void
1588 completion_tracker::add_completion (gdb::unique_xmalloc_ptr<char> name,
1589 completion_match_for_lcd *match_for_lcd,
1590 const char *text, const char *word)
1591 {
1592 if (!maybe_add_completion (std::move (name), match_for_lcd, text, word))
1593 throw_error (MAX_COMPLETIONS_REACHED_ERROR, _("Max completions reached."));
1594 }
1595
1596 /* See completer.h. */
1597
1598 void
1599 completion_tracker::add_completions (completion_list &&list)
1600 {
1601 for (auto &candidate : list)
1602 add_completion (std::move (candidate));
1603 }
1604
1605 /* Helper for the make_completion_match_str overloads. Returns NULL
1606 as an indication that we want MATCH_NAME exactly. It is up to the
1607 caller to xstrdup that string if desired. */
1608
1609 static char *
1610 make_completion_match_str_1 (const char *match_name,
1611 const char *text, const char *word)
1612 {
1613 char *newobj;
1614
1615 if (word == text)
1616 {
1617 /* Return NULL as an indication that we want MATCH_NAME
1618 exactly. */
1619 return NULL;
1620 }
1621 else if (word > text)
1622 {
1623 /* Return some portion of MATCH_NAME. */
1624 newobj = xstrdup (match_name + (word - text));
1625 }
1626 else
1627 {
1628 /* Return some of WORD plus MATCH_NAME. */
1629 size_t len = strlen (match_name);
1630 newobj = (char *) xmalloc (text - word + len + 1);
1631 memcpy (newobj, word, text - word);
1632 memcpy (newobj + (text - word), match_name, len + 1);
1633 }
1634
1635 return newobj;
1636 }
1637
1638 /* See completer.h. */
1639
1640 gdb::unique_xmalloc_ptr<char>
1641 make_completion_match_str (const char *match_name,
1642 const char *text, const char *word)
1643 {
1644 char *newobj = make_completion_match_str_1 (match_name, text, word);
1645 if (newobj == NULL)
1646 newobj = xstrdup (match_name);
1647 return gdb::unique_xmalloc_ptr<char> (newobj);
1648 }
1649
1650 /* See completer.h. */
1651
1652 gdb::unique_xmalloc_ptr<char>
1653 make_completion_match_str (gdb::unique_xmalloc_ptr<char> &&match_name,
1654 const char *text, const char *word)
1655 {
1656 char *newobj = make_completion_match_str_1 (match_name.get (), text, word);
1657 if (newobj == NULL)
1658 return std::move (match_name);
1659 return gdb::unique_xmalloc_ptr<char> (newobj);
1660 }
1661
1662 /* See complete.h. */
1663
1664 completion_result
1665 complete (const char *line, char const **word, int *quote_char)
1666 {
1667 completion_tracker tracker_handle_brkchars;
1668 completion_tracker tracker_handle_completions;
1669 completion_tracker *tracker;
1670
1671 /* The WORD should be set to the end of word to complete. We initialize
1672 to the completion point which is assumed to be at the end of LINE.
1673 This leaves WORD to be initialized to a sensible value in cases
1674 completion_find_completion_word() fails i.e., throws an exception.
1675 See bug 24587. */
1676 *word = line + strlen (line);
1677
1678 try
1679 {
1680 *word = completion_find_completion_word (tracker_handle_brkchars,
1681 line, quote_char);
1682
1683 /* Completers that provide a custom word point in the
1684 handle_brkchars phase also compute their completions then.
1685 Completers that leave the completion word handling to readline
1686 must be called twice. */
1687 if (tracker_handle_brkchars.use_custom_word_point ())
1688 tracker = &tracker_handle_brkchars;
1689 else
1690 {
1691 complete_line (tracker_handle_completions, *word, line, strlen (line));
1692 tracker = &tracker_handle_completions;
1693 }
1694 }
1695 catch (const gdb_exception &ex)
1696 {
1697 return {};
1698 }
1699
1700 return tracker->build_completion_result (*word, *word - line, strlen (line));
1701 }
1702
1703
1704 /* Generate completions all at once. Does nothing if max_completions
1705 is 0. If max_completions is non-negative, this will collect at
1706 most max_completions strings.
1707
1708 TEXT is the caller's idea of the "word" we are looking at.
1709
1710 LINE_BUFFER is available to be looked at; it contains the entire
1711 text of the line.
1712
1713 POINT is the offset in that line of the cursor. You
1714 should pretend that the line ends at POINT. */
1715
1716 void
1717 complete_line (completion_tracker &tracker,
1718 const char *text, const char *line_buffer, int point)
1719 {
1720 if (max_completions == 0)
1721 return;
1722 complete_line_internal (tracker, text, line_buffer, point,
1723 handle_completions);
1724 }
1725
1726 /* Complete on command names. Used by "help". */
1727
1728 void
1729 command_completer (struct cmd_list_element *ignore,
1730 completion_tracker &tracker,
1731 const char *text, const char *word)
1732 {
1733 complete_line_internal (tracker, word, text,
1734 strlen (text), handle_help);
1735 }
1736
1737 /* The corresponding completer_handle_brkchars implementation. */
1738
1739 static void
1740 command_completer_handle_brkchars (struct cmd_list_element *ignore,
1741 completion_tracker &tracker,
1742 const char *text, const char *word)
1743 {
1744 set_rl_completer_word_break_characters
1745 (gdb_completer_command_word_break_characters);
1746 }
1747
1748 /* Complete on signals. */
1749
1750 void
1751 signal_completer (struct cmd_list_element *ignore,
1752 completion_tracker &tracker,
1753 const char *text, const char *word)
1754 {
1755 size_t len = strlen (word);
1756 int signum;
1757 const char *signame;
1758
1759 for (signum = GDB_SIGNAL_FIRST; signum != GDB_SIGNAL_LAST; ++signum)
1760 {
1761 /* Can't handle this, so skip it. */
1762 if (signum == GDB_SIGNAL_0)
1763 continue;
1764
1765 signame = gdb_signal_to_name ((enum gdb_signal) signum);
1766
1767 /* Ignore the unknown signal case. */
1768 if (!signame || strcmp (signame, "?") == 0)
1769 continue;
1770
1771 if (strncasecmp (signame, word, len) == 0)
1772 tracker.add_completion (make_unique_xstrdup (signame));
1773 }
1774 }
1775
1776 /* Bit-flags for selecting what the register and/or register-group
1777 completer should complete on. */
1778
1779 enum reg_completer_target
1780 {
1781 complete_register_names = 0x1,
1782 complete_reggroup_names = 0x2
1783 };
1784 DEF_ENUM_FLAGS_TYPE (enum reg_completer_target, reg_completer_targets);
1785
1786 /* Complete register names and/or reggroup names based on the value passed
1787 in TARGETS. At least one bit in TARGETS must be set. */
1788
1789 static void
1790 reg_or_group_completer_1 (completion_tracker &tracker,
1791 const char *text, const char *word,
1792 reg_completer_targets targets)
1793 {
1794 size_t len = strlen (word);
1795 struct gdbarch *gdbarch;
1796 const char *name;
1797
1798 gdb_assert ((targets & (complete_register_names
1799 | complete_reggroup_names)) != 0);
1800 gdbarch = get_current_arch ();
1801
1802 if ((targets & complete_register_names) != 0)
1803 {
1804 int i;
1805
1806 for (i = 0;
1807 (name = user_reg_map_regnum_to_name (gdbarch, i)) != NULL;
1808 i++)
1809 {
1810 if (*name != '\0' && strncmp (word, name, len) == 0)
1811 tracker.add_completion (make_unique_xstrdup (name));
1812 }
1813 }
1814
1815 if ((targets & complete_reggroup_names) != 0)
1816 {
1817 struct reggroup *group;
1818
1819 for (group = reggroup_next (gdbarch, NULL);
1820 group != NULL;
1821 group = reggroup_next (gdbarch, group))
1822 {
1823 name = reggroup_name (group);
1824 if (strncmp (word, name, len) == 0)
1825 tracker.add_completion (make_unique_xstrdup (name));
1826 }
1827 }
1828 }
1829
1830 /* Perform completion on register and reggroup names. */
1831
1832 void
1833 reg_or_group_completer (struct cmd_list_element *ignore,
1834 completion_tracker &tracker,
1835 const char *text, const char *word)
1836 {
1837 reg_or_group_completer_1 (tracker, text, word,
1838 (complete_register_names
1839 | complete_reggroup_names));
1840 }
1841
1842 /* Perform completion on reggroup names. */
1843
1844 void
1845 reggroup_completer (struct cmd_list_element *ignore,
1846 completion_tracker &tracker,
1847 const char *text, const char *word)
1848 {
1849 reg_or_group_completer_1 (tracker, text, word,
1850 complete_reggroup_names);
1851 }
1852
1853 /* The default completer_handle_brkchars implementation. */
1854
1855 static void
1856 default_completer_handle_brkchars (struct cmd_list_element *ignore,
1857 completion_tracker &tracker,
1858 const char *text, const char *word)
1859 {
1860 set_rl_completer_word_break_characters
1861 (current_language->la_word_break_characters ());
1862 }
1863
1864 /* See definition in completer.h. */
1865
1866 completer_handle_brkchars_ftype *
1867 completer_handle_brkchars_func_for_completer (completer_ftype *fn)
1868 {
1869 if (fn == filename_completer)
1870 return filename_completer_handle_brkchars;
1871
1872 if (fn == location_completer)
1873 return location_completer_handle_brkchars;
1874
1875 if (fn == command_completer)
1876 return command_completer_handle_brkchars;
1877
1878 return default_completer_handle_brkchars;
1879 }
1880
1881 /* Used as brkchars when we want to tell readline we have a custom
1882 word point. We do that by making our rl_completion_word_break_hook
1883 set RL_POINT to the desired word point, and return the character at
1884 the word break point as the break char. This is two bytes in order
1885 to fit one break character plus the terminating null. */
1886 static char gdb_custom_word_point_brkchars[2];
1887
1888 /* Since rl_basic_quote_characters is not completer-specific, we save
1889 its original value here, in order to be able to restore it in
1890 gdb_rl_attempted_completion_function. */
1891 static const char *gdb_org_rl_basic_quote_characters = rl_basic_quote_characters;
1892
1893 /* Get the list of chars that are considered as word breaks
1894 for the current command. */
1895
1896 static char *
1897 gdb_completion_word_break_characters_throw ()
1898 {
1899 /* New completion starting. Get rid of the previous tracker and
1900 start afresh. */
1901 delete current_completion.tracker;
1902 current_completion.tracker = new completion_tracker ();
1903
1904 completion_tracker &tracker = *current_completion.tracker;
1905
1906 complete_line_internal (tracker, NULL, rl_line_buffer,
1907 rl_point, handle_brkchars);
1908
1909 if (tracker.use_custom_word_point ())
1910 {
1911 gdb_assert (tracker.custom_word_point () > 0);
1912 rl_point = tracker.custom_word_point () - 1;
1913
1914 gdb_assert (rl_point >= 0 && rl_point < strlen (rl_line_buffer));
1915
1916 gdb_custom_word_point_brkchars[0] = rl_line_buffer[rl_point];
1917 rl_completer_word_break_characters = gdb_custom_word_point_brkchars;
1918 rl_completer_quote_characters = NULL;
1919
1920 /* Clear this too, so that if we're completing a quoted string,
1921 readline doesn't consider the quote character a delimiter.
1922 If we didn't do this, readline would auto-complete {b
1923 'fun<tab>} to {'b 'function()'}, i.e., add the terminating
1924 \', but, it wouldn't append the separator space either, which
1925 is not desirable. So instead we take care of appending the
1926 quote character to the LCD ourselves, in
1927 gdb_rl_attempted_completion_function. Since this global is
1928 not just completer-specific, we'll restore it back to the
1929 default in gdb_rl_attempted_completion_function. */
1930 rl_basic_quote_characters = NULL;
1931 }
1932
1933 return rl_completer_word_break_characters;
1934 }
1935
1936 char *
1937 gdb_completion_word_break_characters ()
1938 {
1939 /* New completion starting. */
1940 current_completion.aborted = false;
1941
1942 try
1943 {
1944 return gdb_completion_word_break_characters_throw ();
1945 }
1946 catch (const gdb_exception &ex)
1947 {
1948 /* Set this to that gdb_rl_attempted_completion_function knows
1949 to abort early. */
1950 current_completion.aborted = true;
1951 }
1952
1953 return NULL;
1954 }
1955
1956 /* See completer.h. */
1957
1958 const char *
1959 completion_find_completion_word (completion_tracker &tracker, const char *text,
1960 int *quote_char)
1961 {
1962 size_t point = strlen (text);
1963
1964 complete_line_internal (tracker, NULL, text, point, handle_brkchars);
1965
1966 if (tracker.use_custom_word_point ())
1967 {
1968 gdb_assert (tracker.custom_word_point () > 0);
1969 *quote_char = tracker.quote_char ();
1970 return text + tracker.custom_word_point ();
1971 }
1972
1973 gdb_rl_completion_word_info info;
1974
1975 info.word_break_characters = rl_completer_word_break_characters;
1976 info.quote_characters = gdb_completer_quote_characters;
1977 info.basic_quote_characters = rl_basic_quote_characters;
1978
1979 return gdb_rl_find_completion_word (&info, quote_char, NULL, text);
1980 }
1981
1982 /* See completer.h. */
1983
1984 void
1985 completion_tracker::recompute_lowest_common_denominator
1986 (gdb::unique_xmalloc_ptr<char> &&new_match_up)
1987 {
1988 if (m_lowest_common_denominator == NULL)
1989 {
1990 /* We don't have a lowest common denominator yet, so simply take
1991 the whole NEW_MATCH_UP as being it. */
1992 m_lowest_common_denominator = new_match_up.release ();
1993 m_lowest_common_denominator_unique = true;
1994 }
1995 else
1996 {
1997 /* Find the common denominator between the currently-known
1998 lowest common denominator and NEW_MATCH_UP. That becomes the
1999 new lowest common denominator. */
2000 size_t i;
2001 const char *new_match = new_match_up.get ();
2002
2003 for (i = 0;
2004 (new_match[i] != '\0'
2005 && new_match[i] == m_lowest_common_denominator[i]);
2006 i++)
2007 ;
2008 if (m_lowest_common_denominator[i] != new_match[i])
2009 {
2010 m_lowest_common_denominator[i] = '\0';
2011 m_lowest_common_denominator_unique = false;
2012 }
2013 }
2014 }
2015
2016 /* See completer.h. */
2017
2018 void
2019 completion_tracker::advance_custom_word_point_by (int len)
2020 {
2021 m_custom_word_point += len;
2022 }
2023
2024 /* Build a new C string that is a copy of LCD with the whitespace of
2025 ORIG/ORIG_LEN preserved.
2026
2027 Say the user is completing a symbol name, with spaces, like:
2028
2029 "foo ( i"
2030
2031 and the resulting completion match is:
2032
2033 "foo(int)"
2034
2035 we want to end up with an input line like:
2036
2037 "foo ( int)"
2038 ^^^^^^^ => text from LCD [1], whitespace from ORIG preserved.
2039 ^^ => new text from LCD
2040
2041 [1] - We must take characters from the LCD instead of the original
2042 text, since some completions want to change upper/lowercase. E.g.:
2043
2044 "handle sig<>"
2045
2046 completes to:
2047
2048 "handle SIG[QUIT|etc.]"
2049 */
2050
2051 static char *
2052 expand_preserving_ws (const char *orig, size_t orig_len,
2053 const char *lcd)
2054 {
2055 const char *p_orig = orig;
2056 const char *orig_end = orig + orig_len;
2057 const char *p_lcd = lcd;
2058 std::string res;
2059
2060 while (p_orig < orig_end)
2061 {
2062 if (*p_orig == ' ')
2063 {
2064 while (p_orig < orig_end && *p_orig == ' ')
2065 res += *p_orig++;
2066 p_lcd = skip_spaces (p_lcd);
2067 }
2068 else
2069 {
2070 /* Take characters from the LCD instead of the original
2071 text, since some completions change upper/lowercase.
2072 E.g.:
2073 "handle sig<>"
2074 completes to:
2075 "handle SIG[QUIT|etc.]"
2076 */
2077 res += *p_lcd;
2078 p_orig++;
2079 p_lcd++;
2080 }
2081 }
2082
2083 while (*p_lcd != '\0')
2084 res += *p_lcd++;
2085
2086 return xstrdup (res.c_str ());
2087 }
2088
2089 /* See completer.h. */
2090
2091 completion_result
2092 completion_tracker::build_completion_result (const char *text,
2093 int start, int end)
2094 {
2095 completion_list &list = m_entries_vec; /* The completions. */
2096
2097 if (list.empty ())
2098 return {};
2099
2100 /* +1 for the LCD, and +1 for NULL termination. */
2101 char **match_list = XNEWVEC (char *, 1 + list.size () + 1);
2102
2103 /* Build replacement word, based on the LCD. */
2104
2105 match_list[0]
2106 = expand_preserving_ws (text, end - start,
2107 m_lowest_common_denominator);
2108
2109 if (m_lowest_common_denominator_unique)
2110 {
2111 /* We don't rely on readline appending the quote char as
2112 delimiter as then readline wouldn't append the ' ' after the
2113 completion. */
2114 char buf[2] = { (char) quote_char () };
2115
2116 match_list[0] = reconcat (match_list[0], match_list[0],
2117 buf, (char *) NULL);
2118 match_list[1] = NULL;
2119
2120 /* If the tracker wants to, or we already have a space at the
2121 end of the match, tell readline to skip appending
2122 another. */
2123 bool completion_suppress_append
2124 = (suppress_append_ws ()
2125 || match_list[0][strlen (match_list[0]) - 1] == ' ');
2126
2127 return completion_result (match_list, 1, completion_suppress_append);
2128 }
2129 else
2130 {
2131 int ix;
2132
2133 for (ix = 0; ix < list.size (); ++ix)
2134 match_list[ix + 1] = list[ix].release ();
2135 match_list[ix + 1] = NULL;
2136
2137 return completion_result (match_list, list.size (), false);
2138 }
2139 }
2140
2141 /* See completer.h */
2142
2143 completion_result::completion_result ()
2144 : match_list (NULL), number_matches (0),
2145 completion_suppress_append (false)
2146 {}
2147
2148 /* See completer.h */
2149
2150 completion_result::completion_result (char **match_list_,
2151 size_t number_matches_,
2152 bool completion_suppress_append_)
2153 : match_list (match_list_),
2154 number_matches (number_matches_),
2155 completion_suppress_append (completion_suppress_append_)
2156 {}
2157
2158 /* See completer.h */
2159
2160 completion_result::~completion_result ()
2161 {
2162 reset_match_list ();
2163 }
2164
2165 /* See completer.h */
2166
2167 completion_result::completion_result (completion_result &&rhs)
2168 {
2169 if (this == &rhs)
2170 return;
2171
2172 reset_match_list ();
2173 match_list = rhs.match_list;
2174 rhs.match_list = NULL;
2175 number_matches = rhs.number_matches;
2176 rhs.number_matches = 0;
2177 }
2178
2179 /* See completer.h */
2180
2181 char **
2182 completion_result::release_match_list ()
2183 {
2184 char **ret = match_list;
2185 match_list = NULL;
2186 return ret;
2187 }
2188
2189 /* See completer.h */
2190
2191 void
2192 completion_result::sort_match_list ()
2193 {
2194 if (number_matches > 1)
2195 {
2196 /* Element 0 is special (it's the common prefix), leave it
2197 be. */
2198 std::sort (&match_list[1],
2199 &match_list[number_matches + 1],
2200 compare_cstrings);
2201 }
2202 }
2203
2204 /* See completer.h */
2205
2206 void
2207 completion_result::reset_match_list ()
2208 {
2209 if (match_list != NULL)
2210 {
2211 for (char **p = match_list; *p != NULL; p++)
2212 xfree (*p);
2213 xfree (match_list);
2214 match_list = NULL;
2215 }
2216 }
2217
2218 /* Helper for gdb_rl_attempted_completion_function, which does most of
2219 the work. This is called by readline to build the match list array
2220 and to determine the lowest common denominator. The real matches
2221 list starts at match[1], while match[0] is the slot holding
2222 readline's idea of the lowest common denominator of all matches,
2223 which is what readline replaces the completion "word" with.
2224
2225 TEXT is the caller's idea of the "word" we are looking at, as
2226 computed in the handle_brkchars phase.
2227
2228 START is the offset from RL_LINE_BUFFER where TEXT starts. END is
2229 the offset from RL_LINE_BUFFER where TEXT ends (i.e., where
2230 rl_point is).
2231
2232 You should thus pretend that the line ends at END (relative to
2233 RL_LINE_BUFFER).
2234
2235 RL_LINE_BUFFER contains the entire text of the line. RL_POINT is
2236 the offset in that line of the cursor. You should pretend that the
2237 line ends at POINT.
2238
2239 Returns NULL if there are no completions. */
2240
2241 static char **
2242 gdb_rl_attempted_completion_function_throw (const char *text, int start, int end)
2243 {
2244 /* Completers that provide a custom word point in the
2245 handle_brkchars phase also compute their completions then.
2246 Completers that leave the completion word handling to readline
2247 must be called twice. If rl_point (i.e., END) is at column 0,
2248 then readline skips the handle_brkchars phase, and so we create a
2249 tracker now in that case too. */
2250 if (end == 0 || !current_completion.tracker->use_custom_word_point ())
2251 {
2252 delete current_completion.tracker;
2253 current_completion.tracker = new completion_tracker ();
2254
2255 complete_line (*current_completion.tracker, text,
2256 rl_line_buffer, rl_point);
2257 }
2258
2259 completion_tracker &tracker = *current_completion.tracker;
2260
2261 completion_result result
2262 = tracker.build_completion_result (text, start, end);
2263
2264 rl_completion_suppress_append = result.completion_suppress_append;
2265 return result.release_match_list ();
2266 }
2267
2268 /* Function installed as "rl_attempted_completion_function" readline
2269 hook. Wrapper around gdb_rl_attempted_completion_function_throw
2270 that catches C++ exceptions, which can't cross readline. */
2271
2272 char **
2273 gdb_rl_attempted_completion_function (const char *text, int start, int end)
2274 {
2275 /* Restore globals that might have been tweaked in
2276 gdb_completion_word_break_characters. */
2277 rl_basic_quote_characters = gdb_org_rl_basic_quote_characters;
2278
2279 /* If we end up returning NULL, either on error, or simple because
2280 there are no matches, inhibit readline's default filename
2281 completer. */
2282 rl_attempted_completion_over = 1;
2283
2284 /* If the handle_brkchars phase was aborted, don't try
2285 completing. */
2286 if (current_completion.aborted)
2287 return NULL;
2288
2289 try
2290 {
2291 return gdb_rl_attempted_completion_function_throw (text, start, end);
2292 }
2293 catch (const gdb_exception &ex)
2294 {
2295 }
2296
2297 return NULL;
2298 }
2299
2300 /* Skip over the possibly quoted word STR (as defined by the quote
2301 characters QUOTECHARS and the word break characters BREAKCHARS).
2302 Returns pointer to the location after the "word". If either
2303 QUOTECHARS or BREAKCHARS is NULL, use the same values used by the
2304 completer. */
2305
2306 const char *
2307 skip_quoted_chars (const char *str, const char *quotechars,
2308 const char *breakchars)
2309 {
2310 char quote_char = '\0';
2311 const char *scan;
2312
2313 if (quotechars == NULL)
2314 quotechars = gdb_completer_quote_characters;
2315
2316 if (breakchars == NULL)
2317 breakchars = current_language->la_word_break_characters();
2318
2319 for (scan = str; *scan != '\0'; scan++)
2320 {
2321 if (quote_char != '\0')
2322 {
2323 /* Ignore everything until the matching close quote char. */
2324 if (*scan == quote_char)
2325 {
2326 /* Found matching close quote. */
2327 scan++;
2328 break;
2329 }
2330 }
2331 else if (strchr (quotechars, *scan))
2332 {
2333 /* Found start of a quoted string. */
2334 quote_char = *scan;
2335 }
2336 else if (strchr (breakchars, *scan))
2337 {
2338 break;
2339 }
2340 }
2341
2342 return (scan);
2343 }
2344
2345 /* Skip over the possibly quoted word STR (as defined by the quote
2346 characters and word break characters used by the completer).
2347 Returns pointer to the location after the "word". */
2348
2349 const char *
2350 skip_quoted (const char *str)
2351 {
2352 return skip_quoted_chars (str, NULL, NULL);
2353 }
2354
2355 /* Return a message indicating that the maximum number of completions
2356 has been reached and that there may be more. */
2357
2358 const char *
2359 get_max_completions_reached_message (void)
2360 {
2361 return _("*** List may be truncated, max-completions reached. ***");
2362 }
2363 \f
2364 /* GDB replacement for rl_display_match_list.
2365 Readline doesn't provide a clean interface for TUI(curses).
2366 A hack previously used was to send readline's rl_outstream through a pipe
2367 and read it from the event loop. Bleah. IWBN if readline abstracted
2368 away all the necessary bits, and this is what this code does. It
2369 replicates the parts of readline we need and then adds an abstraction
2370 layer, currently implemented as struct match_list_displayer, so that both
2371 CLI and TUI can use it. We copy all this readline code to minimize
2372 GDB-specific mods to readline. Once this code performs as desired then
2373 we can submit it to the readline maintainers.
2374
2375 N.B. A lot of the code is the way it is in order to minimize differences
2376 from readline's copy. */
2377
2378 /* Not supported here. */
2379 #undef VISIBLE_STATS
2380
2381 #if defined (HANDLE_MULTIBYTE)
2382 #define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2)
2383 #define MB_NULLWCH(x) ((x) == 0)
2384 #endif
2385
2386 #define ELLIPSIS_LEN 3
2387
2388 /* gdb version of readline/complete.c:get_y_or_n.
2389 'y' -> returns 1, and 'n' -> returns 0.
2390 Also supported: space == 'y', RUBOUT == 'n', ctrl-g == start over.
2391 If FOR_PAGER is non-zero, then also supported are:
2392 NEWLINE or RETURN -> returns 2, and 'q' -> returns 0. */
2393
2394 static int
2395 gdb_get_y_or_n (int for_pager, const struct match_list_displayer *displayer)
2396 {
2397 int c;
2398
2399 for (;;)
2400 {
2401 RL_SETSTATE (RL_STATE_MOREINPUT);
2402 c = displayer->read_key (displayer);
2403 RL_UNSETSTATE (RL_STATE_MOREINPUT);
2404
2405 if (c == 'y' || c == 'Y' || c == ' ')
2406 return 1;
2407 if (c == 'n' || c == 'N' || c == RUBOUT)
2408 return 0;
2409 if (c == ABORT_CHAR || c < 0)
2410 {
2411 /* Readline doesn't erase_entire_line here, but without it the
2412 --More-- prompt isn't erased and neither is the text entered
2413 thus far redisplayed. */
2414 displayer->erase_entire_line (displayer);
2415 /* Note: The arguments to rl_abort are ignored. */
2416 rl_abort (0, 0);
2417 }
2418 if (for_pager && (c == NEWLINE || c == RETURN))
2419 return 2;
2420 if (for_pager && (c == 'q' || c == 'Q'))
2421 return 0;
2422 displayer->beep (displayer);
2423 }
2424 }
2425
2426 /* Pager function for tab-completion.
2427 This is based on readline/complete.c:_rl_internal_pager.
2428 LINES is the number of lines of output displayed thus far.
2429 Returns:
2430 -1 -> user pressed 'n' or equivalent,
2431 0 -> user pressed 'y' or equivalent,
2432 N -> user pressed NEWLINE or equivalent and N is LINES - 1. */
2433
2434 static int
2435 gdb_display_match_list_pager (int lines,
2436 const struct match_list_displayer *displayer)
2437 {
2438 int i;
2439
2440 displayer->puts (displayer, "--More--");
2441 displayer->flush (displayer);
2442 i = gdb_get_y_or_n (1, displayer);
2443 displayer->erase_entire_line (displayer);
2444 if (i == 0)
2445 return -1;
2446 else if (i == 2)
2447 return (lines - 1);
2448 else
2449 return 0;
2450 }
2451
2452 /* Return non-zero if FILENAME is a directory.
2453 Based on readline/complete.c:path_isdir. */
2454
2455 static int
2456 gdb_path_isdir (const char *filename)
2457 {
2458 struct stat finfo;
2459
2460 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
2461 }
2462
2463 /* Return the portion of PATHNAME that should be output when listing
2464 possible completions. If we are hacking filename completion, we
2465 are only interested in the basename, the portion following the
2466 final slash. Otherwise, we return what we were passed. Since
2467 printing empty strings is not very informative, if we're doing
2468 filename completion, and the basename is the empty string, we look
2469 for the previous slash and return the portion following that. If
2470 there's no previous slash, we just return what we were passed.
2471
2472 Based on readline/complete.c:printable_part. */
2473
2474 static char *
2475 gdb_printable_part (char *pathname)
2476 {
2477 char *temp, *x;
2478
2479 if (rl_filename_completion_desired == 0) /* don't need to do anything */
2480 return (pathname);
2481
2482 temp = strrchr (pathname, '/');
2483 #if defined (__MSDOS__)
2484 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
2485 temp = pathname + 1;
2486 #endif
2487
2488 if (temp == 0 || *temp == '\0')
2489 return (pathname);
2490 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
2491 Look for a previous slash and, if one is found, return the portion
2492 following that slash. If there's no previous slash, just return the
2493 pathname we were passed. */
2494 else if (temp[1] == '\0')
2495 {
2496 for (x = temp - 1; x > pathname; x--)
2497 if (*x == '/')
2498 break;
2499 return ((*x == '/') ? x + 1 : pathname);
2500 }
2501 else
2502 return ++temp;
2503 }
2504
2505 /* Compute width of STRING when displayed on screen by print_filename.
2506 Based on readline/complete.c:fnwidth. */
2507
2508 static int
2509 gdb_fnwidth (const char *string)
2510 {
2511 int width, pos;
2512 #if defined (HANDLE_MULTIBYTE)
2513 mbstate_t ps;
2514 int left, w;
2515 size_t clen;
2516 wchar_t wc;
2517
2518 left = strlen (string) + 1;
2519 memset (&ps, 0, sizeof (mbstate_t));
2520 #endif
2521
2522 width = pos = 0;
2523 while (string[pos])
2524 {
2525 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
2526 {
2527 width += 2;
2528 pos++;
2529 }
2530 else
2531 {
2532 #if defined (HANDLE_MULTIBYTE)
2533 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
2534 if (MB_INVALIDCH (clen))
2535 {
2536 width++;
2537 pos++;
2538 memset (&ps, 0, sizeof (mbstate_t));
2539 }
2540 else if (MB_NULLWCH (clen))
2541 break;
2542 else
2543 {
2544 pos += clen;
2545 w = wcwidth (wc);
2546 width += (w >= 0) ? w : 1;
2547 }
2548 #else
2549 width++;
2550 pos++;
2551 #endif
2552 }
2553 }
2554
2555 return width;
2556 }
2557
2558 /* Print TO_PRINT, one matching completion.
2559 PREFIX_BYTES is number of common prefix bytes.
2560 Based on readline/complete.c:fnprint. */
2561
2562 static int
2563 gdb_fnprint (const char *to_print, int prefix_bytes,
2564 const struct match_list_displayer *displayer)
2565 {
2566 int printed_len, w;
2567 const char *s;
2568 #if defined (HANDLE_MULTIBYTE)
2569 mbstate_t ps;
2570 const char *end;
2571 size_t tlen;
2572 int width;
2573 wchar_t wc;
2574
2575 end = to_print + strlen (to_print) + 1;
2576 memset (&ps, 0, sizeof (mbstate_t));
2577 #endif
2578
2579 printed_len = 0;
2580
2581 /* Don't print only the ellipsis if the common prefix is one of the
2582 possible completions */
2583 if (to_print[prefix_bytes] == '\0')
2584 prefix_bytes = 0;
2585
2586 if (prefix_bytes)
2587 {
2588 char ellipsis;
2589
2590 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
2591 for (w = 0; w < ELLIPSIS_LEN; w++)
2592 displayer->putch (displayer, ellipsis);
2593 printed_len = ELLIPSIS_LEN;
2594 }
2595
2596 s = to_print + prefix_bytes;
2597 while (*s)
2598 {
2599 if (CTRL_CHAR (*s))
2600 {
2601 displayer->putch (displayer, '^');
2602 displayer->putch (displayer, UNCTRL (*s));
2603 printed_len += 2;
2604 s++;
2605 #if defined (HANDLE_MULTIBYTE)
2606 memset (&ps, 0, sizeof (mbstate_t));
2607 #endif
2608 }
2609 else if (*s == RUBOUT)
2610 {
2611 displayer->putch (displayer, '^');
2612 displayer->putch (displayer, '?');
2613 printed_len += 2;
2614 s++;
2615 #if defined (HANDLE_MULTIBYTE)
2616 memset (&ps, 0, sizeof (mbstate_t));
2617 #endif
2618 }
2619 else
2620 {
2621 #if defined (HANDLE_MULTIBYTE)
2622 tlen = mbrtowc (&wc, s, end - s, &ps);
2623 if (MB_INVALIDCH (tlen))
2624 {
2625 tlen = 1;
2626 width = 1;
2627 memset (&ps, 0, sizeof (mbstate_t));
2628 }
2629 else if (MB_NULLWCH (tlen))
2630 break;
2631 else
2632 {
2633 w = wcwidth (wc);
2634 width = (w >= 0) ? w : 1;
2635 }
2636 for (w = 0; w < tlen; ++w)
2637 displayer->putch (displayer, s[w]);
2638 s += tlen;
2639 printed_len += width;
2640 #else
2641 displayer->putch (displayer, *s);
2642 s++;
2643 printed_len++;
2644 #endif
2645 }
2646 }
2647
2648 return printed_len;
2649 }
2650
2651 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
2652 are using it, check for and output a single character for `special'
2653 filenames. Return the number of characters we output.
2654 Based on readline/complete.c:print_filename. */
2655
2656 static int
2657 gdb_print_filename (char *to_print, char *full_pathname, int prefix_bytes,
2658 const struct match_list_displayer *displayer)
2659 {
2660 int printed_len, extension_char, slen, tlen;
2661 char *s, c, *new_full_pathname;
2662 const char *dn;
2663 extern int _rl_complete_mark_directories;
2664
2665 extension_char = 0;
2666 printed_len = gdb_fnprint (to_print, prefix_bytes, displayer);
2667
2668 #if defined (VISIBLE_STATS)
2669 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
2670 #else
2671 if (rl_filename_completion_desired && _rl_complete_mark_directories)
2672 #endif
2673 {
2674 /* If to_print != full_pathname, to_print is the basename of the
2675 path passed. In this case, we try to expand the directory
2676 name before checking for the stat character. */
2677 if (to_print != full_pathname)
2678 {
2679 /* Terminate the directory name. */
2680 c = to_print[-1];
2681 to_print[-1] = '\0';
2682
2683 /* If setting the last slash in full_pathname to a NUL results in
2684 full_pathname being the empty string, we are trying to complete
2685 files in the root directory. If we pass a null string to the
2686 bash directory completion hook, for example, it will expand it
2687 to the current directory. We just want the `/'. */
2688 if (full_pathname == 0 || *full_pathname == 0)
2689 dn = "/";
2690 else if (full_pathname[0] != '/')
2691 dn = full_pathname;
2692 else if (full_pathname[1] == 0)
2693 dn = "//"; /* restore trailing slash to `//' */
2694 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
2695 dn = "/"; /* don't turn /// into // */
2696 else
2697 dn = full_pathname;
2698 s = tilde_expand (dn);
2699 if (rl_directory_completion_hook)
2700 (*rl_directory_completion_hook) (&s);
2701
2702 slen = strlen (s);
2703 tlen = strlen (to_print);
2704 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
2705 strcpy (new_full_pathname, s);
2706 if (s[slen - 1] == '/')
2707 slen--;
2708 else
2709 new_full_pathname[slen] = '/';
2710 new_full_pathname[slen] = '/';
2711 strcpy (new_full_pathname + slen + 1, to_print);
2712
2713 #if defined (VISIBLE_STATS)
2714 if (rl_visible_stats)
2715 extension_char = stat_char (new_full_pathname);
2716 else
2717 #endif
2718 if (gdb_path_isdir (new_full_pathname))
2719 extension_char = '/';
2720
2721 xfree (new_full_pathname);
2722 to_print[-1] = c;
2723 }
2724 else
2725 {
2726 s = tilde_expand (full_pathname);
2727 #if defined (VISIBLE_STATS)
2728 if (rl_visible_stats)
2729 extension_char = stat_char (s);
2730 else
2731 #endif
2732 if (gdb_path_isdir (s))
2733 extension_char = '/';
2734 }
2735
2736 xfree (s);
2737 if (extension_char)
2738 {
2739 displayer->putch (displayer, extension_char);
2740 printed_len++;
2741 }
2742 }
2743
2744 return printed_len;
2745 }
2746
2747 /* GDB version of readline/complete.c:complete_get_screenwidth. */
2748
2749 static int
2750 gdb_complete_get_screenwidth (const struct match_list_displayer *displayer)
2751 {
2752 /* Readline has other stuff here which it's not clear we need. */
2753 return displayer->width;
2754 }
2755
2756 extern int _rl_completion_prefix_display_length;
2757 extern int _rl_print_completions_horizontally;
2758
2759 EXTERN_C int _rl_qsort_string_compare (const void *, const void *);
2760 typedef int QSFUNC (const void *, const void *);
2761
2762 /* GDB version of readline/complete.c:rl_display_match_list.
2763 See gdb_display_match_list for a description of MATCHES, LEN, MAX.
2764 Returns non-zero if all matches are displayed. */
2765
2766 static int
2767 gdb_display_match_list_1 (char **matches, int len, int max,
2768 const struct match_list_displayer *displayer)
2769 {
2770 int count, limit, printed_len, lines, cols;
2771 int i, j, k, l, common_length, sind;
2772 char *temp, *t;
2773 int page_completions = displayer->height != INT_MAX && pagination_enabled;
2774
2775 /* Find the length of the prefix common to all items: length as displayed
2776 characters (common_length) and as a byte index into the matches (sind) */
2777 common_length = sind = 0;
2778 if (_rl_completion_prefix_display_length > 0)
2779 {
2780 t = gdb_printable_part (matches[0]);
2781 temp = strrchr (t, '/');
2782 common_length = temp ? gdb_fnwidth (temp) : gdb_fnwidth (t);
2783 sind = temp ? strlen (temp) : strlen (t);
2784
2785 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
2786 max -= common_length - ELLIPSIS_LEN;
2787 else
2788 common_length = sind = 0;
2789 }
2790
2791 /* How many items of MAX length can we fit in the screen window? */
2792 cols = gdb_complete_get_screenwidth (displayer);
2793 max += 2;
2794 limit = cols / max;
2795 if (limit != 1 && (limit * max == cols))
2796 limit--;
2797
2798 /* If cols == 0, limit will end up -1 */
2799 if (cols < displayer->width && limit < 0)
2800 limit = 1;
2801
2802 /* Avoid a possible floating exception. If max > cols,
2803 limit will be 0 and a divide-by-zero fault will result. */
2804 if (limit == 0)
2805 limit = 1;
2806
2807 /* How many iterations of the printing loop? */
2808 count = (len + (limit - 1)) / limit;
2809
2810 /* Watch out for special case. If LEN is less than LIMIT, then
2811 just do the inner printing loop.
2812 0 < len <= limit implies count = 1. */
2813
2814 /* Sort the items if they are not already sorted. */
2815 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
2816 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
2817
2818 displayer->crlf (displayer);
2819
2820 lines = 0;
2821 if (_rl_print_completions_horizontally == 0)
2822 {
2823 /* Print the sorted items, up-and-down alphabetically, like ls. */
2824 for (i = 1; i <= count; i++)
2825 {
2826 for (j = 0, l = i; j < limit; j++)
2827 {
2828 if (l > len || matches[l] == 0)
2829 break;
2830 else
2831 {
2832 temp = gdb_printable_part (matches[l]);
2833 printed_len = gdb_print_filename (temp, matches[l], sind,
2834 displayer);
2835
2836 if (j + 1 < limit)
2837 for (k = 0; k < max - printed_len; k++)
2838 displayer->putch (displayer, ' ');
2839 }
2840 l += count;
2841 }
2842 displayer->crlf (displayer);
2843 lines++;
2844 if (page_completions && lines >= (displayer->height - 1) && i < count)
2845 {
2846 lines = gdb_display_match_list_pager (lines, displayer);
2847 if (lines < 0)
2848 return 0;
2849 }
2850 }
2851 }
2852 else
2853 {
2854 /* Print the sorted items, across alphabetically, like ls -x. */
2855 for (i = 1; matches[i]; i++)
2856 {
2857 temp = gdb_printable_part (matches[i]);
2858 printed_len = gdb_print_filename (temp, matches[i], sind, displayer);
2859 /* Have we reached the end of this line? */
2860 if (matches[i+1])
2861 {
2862 if (i && (limit > 1) && (i % limit) == 0)
2863 {
2864 displayer->crlf (displayer);
2865 lines++;
2866 if (page_completions && lines >= displayer->height - 1)
2867 {
2868 lines = gdb_display_match_list_pager (lines, displayer);
2869 if (lines < 0)
2870 return 0;
2871 }
2872 }
2873 else
2874 for (k = 0; k < max - printed_len; k++)
2875 displayer->putch (displayer, ' ');
2876 }
2877 }
2878 displayer->crlf (displayer);
2879 }
2880
2881 return 1;
2882 }
2883
2884 /* Utility for displaying completion list matches, used by both CLI and TUI.
2885
2886 MATCHES is the list of strings, in argv format, LEN is the number of
2887 strings in MATCHES, and MAX is the length of the longest string in
2888 MATCHES. */
2889
2890 void
2891 gdb_display_match_list (char **matches, int len, int max,
2892 const struct match_list_displayer *displayer)
2893 {
2894 /* Readline will never call this if complete_line returned NULL. */
2895 gdb_assert (max_completions != 0);
2896
2897 /* complete_line will never return more than this. */
2898 if (max_completions > 0)
2899 gdb_assert (len <= max_completions);
2900
2901 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
2902 {
2903 char msg[100];
2904
2905 /* We can't use *query here because they wait for <RET> which is
2906 wrong here. This follows the readline version as closely as possible
2907 for compatibility's sake. See readline/complete.c. */
2908
2909 displayer->crlf (displayer);
2910
2911 xsnprintf (msg, sizeof (msg),
2912 "Display all %d possibilities? (y or n)", len);
2913 displayer->puts (displayer, msg);
2914 displayer->flush (displayer);
2915
2916 if (gdb_get_y_or_n (0, displayer) == 0)
2917 {
2918 displayer->crlf (displayer);
2919 return;
2920 }
2921 }
2922
2923 if (gdb_display_match_list_1 (matches, len, max, displayer))
2924 {
2925 /* Note: MAX_COMPLETIONS may be -1 or zero, but LEN is always > 0. */
2926 if (len == max_completions)
2927 {
2928 /* The maximum number of completions has been reached. Warn the user
2929 that there may be more. */
2930 const char *message = get_max_completions_reached_message ();
2931
2932 displayer->puts (displayer, message);
2933 displayer->crlf (displayer);
2934 }
2935 }
2936 }
2937
2938 void
2939 _initialize_completer (void)
2940 {
2941 add_setshow_zuinteger_unlimited_cmd ("max-completions", no_class,
2942 &max_completions, _("\
2943 Set maximum number of completion candidates."), _("\
2944 Show maximum number of completion candidates."), _("\
2945 Use this to limit the number of candidates considered\n\
2946 during completion. Specifying \"unlimited\" or -1\n\
2947 disables limiting. Note that setting either no limit or\n\
2948 a very large limit can make completion slow."),
2949 NULL, NULL, &setlist, &showlist);
2950 }
This page took 0.091104 seconds and 4 git commands to generate.