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