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