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