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